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

import { useUserRecords } from "../hooks/useUserRecords";
import { useSignatureListWithPresigned } from "../hooks/useSignatureAndTeeterWithPresigned";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useTranslation } from "react-i18next";

interface SendRecordProps {
  recordId: string;
  onSuccess: () => void;
  onClose: () => void;
}

const SendRecord: React.FC<SendRecordProps> = ({
  recordId,
  onSuccess,
  onClose,
}) => {
  const { directDispatch, isDirectDispatching } = useUserRecords();
  const { userDetails } = useAuthUser();
  const { data: signatureData } = useSignatureListWithPresigned(
    userDetails?.id || "",
  );
  const { t } = useTranslation();

  const handleSendDirect = useCallback(async () => {
    const signatureId = signatureData?.signatureId;

    if (!signatureId) {
      toast.error(t("userRecord.noSignatureForDirectSend"));
      return;
    }

    try {
      await directDispatch({ recordId, signatureId });
      onSuccess();
    } catch (error) {
      // Error toast is handled in useUserRecords hook
      console.error(error);
    }
  }, [recordId, signatureData, directDispatch, onSuccess, t]);

  return (
    <EnhancedDynamicModal
      open={true}
      onClose={onClose}
      title={t("userRecord.SendDirectRecordTitle")}
      description={t("userRecord.SendDirectRecordDescription")}
      actionConfig={{
        type: "custom",
        onAction: handleSendDirect,
        confirmText: isDirectDispatching
          ? t("userRecord.Sending")
          : t("userRecord.Send"),
        confirmVariant: "default",
        isLoading: isDirectDispatching,
      }}
    />
  );
};

export default SendRecord;
