import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { Button } from "@/shared/common/ui/button";
import { Loader2, AlertTriangle } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { deleteUnit } from "@/user-management/services/api/unitService";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";

interface PermanentDeleteUnitDialogProps {
  unitName: string;
  unitId: string;
  isOpen: boolean;
  onClose: () => void;
}

export const PermanentDeleteUnitDialog: React.FC<PermanentDeleteUnitDialogProps> = ({
  unitName,
  unitId,
  isOpen,
  onClose,
}) => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [isDeleting, setIsDeleting] = useState(false);

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      await deleteUnit(unitId);
      toast.success(t("archive.unitDeletedPermanently", "Unit permanently deleted"));
      queryClient.invalidateQueries({ queryKey: ["unitList"] });
      queryClient.invalidateQueries({ queryKey: ["unitChildren"] });
      queryClient.invalidateQueries({ queryKey: ["archived-units"] });
      onClose();
    } catch (error: any) {
      // Check if error is due to related entities (units or positions)
      if (error?.response?.status === 400 && error?.response?.data?.message) {
        const errorMessage = error?.response?.data?.message;
        
        // Check if it's a position-related error
        if (errorMessage.includes("Referenced Entity") || errorMessage.includes("referenced")) {
          toast.error(
            t("archive.cannotDeleteUnitWithEntities", "Cannot delete unit with related positions. Please delete or reassign all positions first."),
            {
              description: t("archive.deleteRelatedEntitiesFirst", "Remove all related entities before attempting deletion.")
            }
          );
        } else if (errorMessage.includes("position")) {
          toast.error(
            t("archive.cannotDeleteUnitWithPositions", "Cannot delete unit that has related positions. Please delete or reassign all positions first."),
            {
              description: t("archive.deleteRelatedEntitiesFirst", "Remove all related entities before attempting deletion.")
            }
          );
        } else {
          toast.error(
            t("archive.cannotDeleteUnit", "Cannot delete unit"),
            {
              description: t("archive.deleteRelatedEntitiesFirst", "Remove all related entities before attempting deletion.")
            }
          );
        }
      } else {
        toast.error(t("archive.deleteUnitFailed", "Failed to delete unit"));
      }
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <AlertDialog open={isOpen} onOpenChange={onClose}>
      <AlertDialogContent className="max-w-md">
        <AlertDialogHeader>
          <div className="flex items-start gap-3">
            <div className="flex-shrink-0 mt-0.5">
              <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400" />
            </div>
            <div className="flex-1">
              <AlertDialogTitle className="text-lg font-semibold text-red-900 dark:text-red-100">
                {t("archive.permanentDeleteWarning", "Permanent Deletion")}
              </AlertDialogTitle>
              <AlertDialogDescription className="mt-2 text-sm text-gray-700 dark:text-gray-300">
                {t("archive.deletePermanentlyDescription", "This will permanently delete the unit")} <strong className="font-semibold">{unitName}</strong>. {t("archive.cannotBeUndone", "This action cannot be undone.")}
              </AlertDialogDescription>
            </div>
          </div>
        </AlertDialogHeader>

        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800/50 rounded-md p-3 my-2">
          <p className="text-sm text-red-800 dark:text-red-200">
            {t("archive.permanentDeleteExplanation", "Once deleted, this unit cannot be recovered. Make sure all related positions have been removed first.")}
          </p>
        </div>

        <AlertDialogFooter className="gap-2">
          <AlertDialogCancel disabled={isDeleting} className="sm:w-auto">
            {t("common.Cancel", "Cancel")}
          </AlertDialogCancel>
          <Button
            variant="destructive"
            onClick={handleDelete}
            disabled={isDeleting}
            className="gap-2"
          >
            {isDeleting && <Loader2 className="w-4 h-4 animate-spin" />}
            {t("archive.deletePermanently", "Delete Permanently")}
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
};
