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

import { User } from "@/store/models/User.model";
import { UserModal } from "@/components/features/users/UserModal";
import { DeleteUserModal } from "@/components/features/users/DeleteUserModal";
import { LockUserModal } from "@/components/features/users/LockUserModal";
import { AdminModal } from "@/components/features/admins/AdminModal";
import { OperationMode } from "@/constants/operationModeEnum";
import { RoleEnum } from "@/constants/roleEnum";
import {
  useUpdateUserMutation,
  useDeleteUserMutation,
  useLockUserMutation,
  useGetUserByIdQuery,
} from "@/store/api/usersApi";
import { AppSnackbar } from "@/components/ui/AppSnackbar";

interface PersonalActionsProps {
  user: User;
  isLoading: boolean;
}

export const PersonalActions = ({ user, isLoading }: PersonalActionsProps) => {
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [lockModalVisible, setLockModalVisible] = useState(false);
  const [snackbarVisible, setSnackbarVisible] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");

  const { refetch } = useGetUserByIdQuery(user.id, { skip: !user.id });

  const [updateUser, { isLoading: isUpdating }] = useUpdateUserMutation();
  const [deleteUser, { isLoading: isDeleting }] = useDeleteUserMutation();
  const [lockUser, { isLoading: isLocking }] = useLockUserMutation();

  const showSnackbar = (message: string) => {
    setSnackbarMessage(message);
    setSnackbarVisible(true);
  };

  const handleEdit = () => {
    setEditModalVisible(true);
  };

  const handleDelete = () => {
    setDeleteModalVisible(true);
  };

  const handleLock = () => {
    setLockModalVisible(true);
  };

  const handleUpdateUser = async (updatedUser: Partial<User>) => {
    try {
      await updateUser(updatedUser).unwrap();
      showSnackbar(
        `${updatedUser.firstName} ${updatedUser.lastName} updated successfully`
      );
      setEditModalVisible(false);
      refetch();
    } catch (error) {
      showSnackbar("Error updating user");
      console.error("Error updating user:", error);
    }
  };

  const handleDeleteUser = async (userToDelete: User) => {
    try {
      await deleteUser(userToDelete.id).unwrap();
      showSnackbar(
        `${userToDelete.firstName} ${userToDelete.lastName} deleted successfully`
      );
      setDeleteModalVisible(false);
      refetch();
    } catch (error) {
      showSnackbar("Error deleting user");
      console.error("Error deleting user:", error);
    }
  };

  const handleLockUser = async (userToLock: User) => {
    try {
      await lockUser(userToLock.id).unwrap();
      const action = userToLock.isLocked ? "unlocked" : "locked";
      showSnackbar(
        `${userToLock.firstName} ${userToLock.lastName} ${action} successfully`
      );
      setLockModalVisible(false);
      refetch();
    } catch (error) {
      showSnackbar("Error updating user lock status");
      console.error("Error locking/unlocking user:", error);
    }
  };

  return (
    <>
      <View className="flex-row justify-end">
        <IconButton
          icon="pencil-outline"
          onPress={handleEdit}
          size={24}
          iconColor="#7A757C"
          disabled={isLoading}
        />
        <IconButton
          icon="lock-outline"
          onPress={handleLock}
          size={24}
          iconColor={user.isLocked ? "#F83434" : "#7A757C"}
          disabled={isLoading}
        />
        <IconButton
          icon="delete-outline"
          onPress={handleDelete}
          size={24}
          iconColor="#7A757C"
          disabled={isLoading}
        />
      </View>

      {user.role === RoleEnum.ADMIN || user.role === RoleEnum.MANAGER ? (
        <AdminModal
          visible={editModalVisible}
          onClose={() => setEditModalVisible(false)}
          onSubmit={handleUpdateUser}
          admin={user}
          mode={OperationMode.EDIT}
          isLoading={isUpdating}
        />
      ) : (
        <UserModal
          visible={editModalVisible}
          onClose={() => setEditModalVisible(false)}
          onSubmit={handleUpdateUser}
          user={user}
          mode={OperationMode.EDIT}
          isLoading={isUpdating}
        />
      )}

      <DeleteUserModal
        visible={deleteModalVisible}
        user={user}
        onDismiss={() => setDeleteModalVisible(false)}
        onDelete={handleDeleteUser}
        isLoading={isDeleting}
      />

      <LockUserModal
        visible={lockModalVisible}
        user={user}
        onDismiss={() => setLockModalVisible(false)}
        onLock={handleLockUser}
        isLoading={isLocking}
      />

      <AppSnackbar
        visible={snackbarVisible}
        onDismiss={() => setSnackbarVisible(false)}
        action={{ label: "Close", onPress: () => setSnackbarVisible(false) }}
      >
        {snackbarMessage}
      </AppSnackbar>
    </>
  );
};
