import EnhancedDynamicModal from '@/record-management/common/EnhancedDynamicModal';
import { usePositionTypes } from '@/user-management/hooks/usePositionTypes';
import React, { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

interface DeletePositionTypesProps {
  id: string;
  onSuccess: () => void;
  onClose: () => void;
}


const DeletePositionTypes = (
    {
    id,
    onSuccess,
    onClose
}: DeletePositionTypesProps

) => {
    const { t } = useTranslation();
  const { deletePositionType, refetch } = usePositionTypes({ id });

    const handleDelete = useCallback(async()=>{
        try{
        await deletePositionType.mutateAsync(id);
        await refetch();
        onSuccess();
        toast.success("Position type deleted successfully");

        }catch(error) {
            if (
              typeof error === "object" &&
              error !== null &&
              "statusCode" in error &&
              (error as any).statusCode === 400 &&
              "response" in error &&
              (error as any).response &&
              "data" in (error as any).response &&
              (error as any).response.data &&
              "code" in (error as any).response.data &&
              (error as any).response.data.code === "23503"
            ) {
              toast.error(
                "This Position Type is still in use and cannot be deleted."
              );
            } else {
              toast.error("An unexpected error occurred.");
            }
            console.error("Error deleting position type:", error);
            toast.error("Error deleting position type");
        }
    },[ deletePositionType, id ]);

  return (
    <EnhancedDynamicModal
      open={true}
      onClose={onClose}
      title={t("userRecord.Delete Record")}
      actionConfig={{
        type: "delete",
        onAction: handleDelete,
        confirmText: t("userRecord.Confirm Delete"),
        confirmVariant: "default",
      }}
    />
  );
};

export default DeletePositionTypes;