import { useState } from "react";
import { View, Text } from "react-native";
import { Dialog, IconButton } from "react-native-paper";

import { DialogContainer } from "@/components/ui/DialogContainer";
import { User } from "@/store/models/User.model";
import { Button } from "@/components/ui/Button";
import { LoadingSpinner } from "@/components/ui/LoadingSpinner";

interface DeleteUserModalProps {
  visible: boolean;
  user: User | null;
  onDismiss: () => void;
  onDelete: (user: User) => void;
  isLoading?: boolean;
}

export const DeleteUserModal = ({
  visible,
  user,
  onDismiss,
  onDelete,
  isLoading = false,
}: DeleteUserModalProps) => {
  const [error, setError] = useState<string | null>(null);

  if (!user) return null;

  const handleDelete = () => {
    try {
      setError(null);
      onDelete(user);
    } catch (err) {
      setError("Failed to delete user. Please try again.");
      console.error("Error in UserDeleteModal:", err);
    }
  };

  return (
    <DialogContainer visible={visible} onDismiss={onDismiss}>
      <Dialog.Title>
        <View className="w-full flex-row items-center justify-between">
          <View className="flex-1">
            <Text className="pr-3">Delete User</Text>
          </View>

          <View style={{ alignSelf: "flex-start" }}>
            <IconButton
              icon="close"
              size={20}
              onPress={onDismiss}
              disabled={isLoading}
              accessibilityLabel="Close dialog"
              style={{ margin: 0 }}
            />
          </View>
        </View>
      </Dialog.Title>
      <Dialog.Content>
        <Text>
          Are you sure you want to delete {user.firstName} {user.lastName}?
        </Text>
        {error && <Text className="text-highRisk mt-2">{error}</Text>}
      </Dialog.Content>
      <Dialog.Actions>
        <Button className="ml-2!" onPress={handleDelete} disabled={isLoading}>
          Delete
        </Button>
      </Dialog.Actions>
      {isLoading && (
        <View
          className="absolute inset-0 bg-gray-500/30 flex items-center justify-center"
          pointerEvents="auto"
          style={{ zIndex: 1000, top: 0, right: 0, bottom: 0, left: 0 }}
        >
          <LoadingSpinner size={16} />
        </View>
      )}
    </DialogContainer>
  );
};
