"use client";

import React from "react";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "@/app/redux/store";
import { deleteUser, clearError } from "@/app/redux/user/userSlice";
import { IUser } from "../../Pages/Admin/Users/interfaces";
import Modal from "@/app/components/Modal/Modal";
import Spinner from "@/app/components/Spinner/Spinner";
import { RootState } from "@/app/redux/store";
import { selectUser } from "@/app/redux/auth/selectors";
import "./DeleteUser.scss";

interface DeleteUserProps {
  open: boolean;
  onClose: () => void;
  user: IUser | null;
}

const DeleteUser: React.FC<DeleteUserProps> = ({ open, onClose, user }) => {
  const dispatch = useDispatch<AppDispatch>();
  const router = useRouter();
  const { status, error } = useSelector((state: RootState) => state.user);
  const currentUser = useSelector(selectUser);

  const loading = status === "loading";
  const isSelfDeletion = currentUser?.id === user?.id;

  const handleDelete = async () => {
    if (!user?.id) {
      toast.error("No user selected for deletion");
      return;
    }

    if (isSelfDeletion) {
      toast.error("You cannot delete your own account");
      return;
    }

    try {
      const resultAction = await dispatch(deleteUser(user.id));

      if (deleteUser.fulfilled.match(resultAction)) {
        toast.success(
          resultAction.payload.message || "User deleted successfully"
        );
        dispatch(clearError());
        router.refresh();
        onClose();
      } else if (deleteUser.rejected.match(resultAction)) {
        toast.error(
          (resultAction.payload as string) || "Failed to delete user"
        );
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      toast.error(error.message || "An unexpected error occurred");
    }
  };

  const handleClose = () => {
    if (!loading) {
      dispatch(clearError());
      onClose();
    }
  };

  return (
    <Modal open={open} onClose={handleClose} title="Delete User">
      <div className="delete-user__content">
        <div className="delete-user__warning">
          <p className="delete-user__warning-text">
            Are you sure you want to delete this user? This action cannot be
            undone.
          </p>
        </div>

        {user && (
          <div className="delete-user__user-info">
            <div className="delete-user__row">
              <label className="delete-user__label">Username</label>
              <div className="delete-user__value">{user.username}</div>
            </div>
            <div className="delete-user__row">
              <label className="delete-user__label">Name</label>
              <div className="delete-user__value">
                {user.first_name} {user.last_name}
              </div>
            </div>
            <div className="delete-user__row">
              <label className="delete-user__label">Email</label>
              <div className="delete-user__value">{user.email}</div>
            </div>
          </div>
        )}

        {error && (
          <div className="delete-user__error">
            <span>{error}</span>
          </div>
        )}

        <div className="delete-user__actions">
          <button
            type="button"
            onClick={handleClose}
            disabled={loading}
            className="delete-user__button delete-user__button--cancel"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleDelete}
            disabled={loading || isSelfDeletion}
            className="delete-user__button delete-user__button--delete"
          >
            {loading ? (
              <>
                <Spinner size="small" color="#fff" />
                Deleting...
              </>
            ) : (
              "Delete User"
            )}
          </button>
        </div>
      </div>
    </Modal>
  );
};

export default DeleteUser;
