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 LockUserModalProps {
  visible: boolean;
  user: User | null;
  onDismiss: () => void;
  onLock: (user: User) => void;
  isLoading?: boolean;
}

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

  if (!user) return null;

  const action = user.isLocked ? "unlock" : "lock";
  const actionTitle = action.charAt(0).toUpperCase() + action.slice(1);

  const handleLock = () => {
    try {
      setError(null);
      onLock(user);
    } catch (err) {
      setError(`Failed to ${action} user. Please try again.`);
      console.error(`Error in UserLockModal (${action}):`, 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">{actionTitle} 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 {action} {user.firstName} {user.lastName}?
        </Text>
        {error && <Text className="text-highRisk mt-2">{error}</Text>}
      </Dialog.Content>
      <Dialog.Actions>
        <Button className="ml-2!" onPress={handleLock} disabled={isLoading}>
          {actionTitle}
        </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>
  );
};
