import { useMemo, useState } from "react";
import { View, TouchableOpacity } from "react-native";
import {
  Avatar,
  Divider,
  Menu,
  Text,
  Chip,
  IconButton,
} from "react-native-paper";

import { useAuthContext } from "@/auth/AuthContext";
import { getInitials, getRoleLabel } from "@/utils/userUtils";

export const UserButton = () => {
  const { user, logout } = useAuthContext();
  const [visible, setVisible] = useState(false);

  const initials = useMemo(
    () => getInitials(user?.firstName, user?.lastName),
    [user?.firstName, user?.lastName]
  );

  if (!user) return null;

  return (
    <View className="flex-row items-center">
      <Menu
        visible={visible}
        onDismiss={() => setVisible(false)}
        anchor={
          <TouchableOpacity
            accessibilityRole="button"
            onPress={() => setVisible(true)}
            className="ml-3"
          >
            {user.imageUrl ? (
              <Avatar.Image size={32} source={{ uri: user.imageUrl }} />
            ) : (
              <Avatar.Text size={32} label={initials} />
            )}
          </TouchableOpacity>
        }
        contentStyle={{
          minWidth: 300,
          borderRadius: 12,
          overflow: "hidden",
          padding: 0,
        }}
      >
        <View
          style={{
            paddingHorizontal: 14,
            paddingVertical: 12,
            backgroundColor: "#F7F7F8",
          }}
        >
          <View style={{ flexDirection: "row", alignItems: "center" }}>
            {user.imageUrl ? (
              <Avatar.Image size={44} source={{ uri: user.imageUrl }} />
            ) : (
              <Avatar.Text size={44} label={initials} />
            )}
            <View
              style={{
                flexShrink: 1,
                maxWidth: 500,
                marginLeft: 8,
              }}
            >
              <Text variant="titleSmall" numberOfLines={10}>
                {user.firstName} {user.lastName}
              </Text>
              <Text variant="bodySmall" style={{ opacity: 0.7 }}>
                {user.email}
              </Text>
            </View>

            <View style={{ alignSelf: "flex-start", marginLeft: "auto" }}>
              <IconButton
                icon="close"
                size={20}
                onPress={() => setVisible(false)}
                accessibilityLabel="Close dialog"
                style={{ margin: 0 }}
              />
            </View>
          </View>
          <View style={{ height: 10 }} />
          <View style={{ flexDirection: "column", flexWrap: "wrap" }}>
            <Chip compact>{getRoleLabel(user.role)}</Chip>
          </View>
        </View>
        <Divider />
        <Menu.Item
          title="Sign out"
          leadingIcon="logout"
          onPress={async () => {
            setVisible(false);
            await logout();
          }}
        />
      </Menu>
    </View>
  );
};
