import React, { useCallback } from "react";
import { toast } from "sonner";
import EnhancedDynamicModal from "@/record-management/common/EnhancedDynamicModal";

import { useApprovalTasks } from "../hooks/useApprovalTasks";
import Loader from "@/record-management/components/Loader/loader";
import { useTranslation } from "react-i18next";

interface ForwardRecordProps {
  recordId: string;
  delegateId?: string; // Optional delegate ID if needed
  onSuccess: () => void;
  onClose: () => void;
}

const ForwardRecord: React.FC<ForwardRecordProps> = ({
  recordId,
  delegateId,
  onSuccess,
  onClose,
}) => {
  const { submitRecord, submitRecordLoading, refetch } = useApprovalTasks();
  const { t } = useTranslation();

  const handleForward = useCallback(async () => {
    if (!recordId) return;
    try {
      await submitRecord({
        id: recordId,
        delegatorId: delegateId || undefined,
      });
      await refetch();
      toast.success(t("userRecord.Record forwarded successfully"));
      onSuccess();
    } catch {
      // Hook's onError already routes through handleError; swallow here
      // to keep the modal closed cleanly without a second toast.
    }
  }, [recordId, submitRecord, delegateId, refetch, onSuccess, t]);

  return (
    <>
      <EnhancedDynamicModal
        open={true}
        onClose={onClose}
        title={t("userRecord.Forward Record")}
        actionConfig={{
          type: "forward",
          onAction: handleForward,
          confirmText: t("userRecord.Confirm Forward"),
          confirmVariant: "default",
          isLoading: submitRecordLoading,
        }}
      />
      {submitRecordLoading && (
        <Loader mode="inline" className="mt-2" showLabel={false} />
      )}
    </>
  );
};

export default ForwardRecord;
