import { useCallback } from "react";
import { toast } from "sonner";
import EnhancedDynamicModal from "@/record-management/common/EnhancedDynamicModal";
import React from "react";
import { useTranslation } from "react-i18next";
import { useDelegations } from "../hooks/useDelegations";

interface DeleteDelegationProps {
  delegateId: string;
  onSuccess: () => void;
  onClose: () => void;
}

const DeleteDelegation: React.FC<DeleteDelegationProps> = ({
  delegateId,
  onSuccess,
  onClose,
}) => {
  const { deleteDelegationAsync, refetch } = useDelegations();
  const { t } = useTranslation();

  const handleDelete = useCallback(
    async (data?: Record<string, unknown>) => {
      if (!delegateId) throw new Error("Invalid Delegation ID");
      const reason = String(data?.reason ?? "").trim();
      if (!reason) {
        toast.error(
          t(
            "delegation.deleteReasonRequired",
            "Please provide a reason for deletion.",
          ),
        );
        throw new Error("reason required");
      }

      await deleteDelegationAsync({
          id: delegateId,
          comment: reason,
        });
      refetch();
      onSuccess();
    },
    [delegateId, deleteDelegationAsync, refetch, onSuccess, t],
  );

  return (
    <EnhancedDynamicModal
      open={true}
      onClose={onClose}
      title={t("userRecord.Delete Delegation")}
      description={t(
        "delegation.deleteDescription",
        "Provide a reason for ending this delegation.",
      )}
      actionConfig={{
        type: "delete",
        onAction: handleDelete,
        confirmText: t("userRecord.Confirm Delete"),
        confirmVariant: "destructive",
      }}
      formConfig={{
        fields: [
          {
            name: "reason",
            label: t("delegation.deleteReasonLabel", "Reason"),
            type: "textarea",
            placeholder: t(
              "delegation.deleteReasonPlaceholder",
              "Why are you ending this delegation?",
            ),
            required: true,
            rules: {
              required: t(
                "delegation.deleteReasonRequired",
                "Please provide a reason for deletion.",
              ),
              validate: (value: string) =>
                value && value.trim().length > 0
                  ? true
                  : t(
                      "delegation.deleteReasonRequired",
                      "Please provide a reason for deletion.",
                    ),
            },
          },
        ],
        defaultValues: { reason: "" },
      }}
    />
  );
};

export default DeleteDelegation;
