import React, { useCallback, useState } from "react";
import { toast } from "sonner";
import EnhancedDynamicModal from "@/record-management/common/EnhancedDynamicModal";
import Loader from "@/record-management/components/Loader/loader";
import { useTranslation } from "react-i18next";
import { useApprovalTasks } from "../../hooks/useApprovalTasks";

interface UnderReviewRecordProps {
  recordId: string;

  onSuccess: () => void;
  onClose: () => void;
}

const UnderReviewRecord: React.FC<UnderReviewRecordProps> = ({
  recordId,

  onSuccess,
  onClose,
}) => {
  const { makeRecordUnderReview, refetch } = useApprovalTasks();
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();

  const handleMakeReview = useCallback(async () => {
    if (!recordId) {
      toast.error("Invalid record ID");
      return;
    }
    try {
      setLoading(true);

      await makeRecordUnderReview({
        id: recordId,
      });
      await refetch();
      onSuccess();
      toast.success(t("userRecord.Record forwarded successfully"));
    } catch (error) {
      toast.error(t("userRecord.Failed to forward the record"));
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [recordId, makeRecordUnderReview, refetch, onSuccess]);

  return (
    <>
      <EnhancedDynamicModal
        open={true}
        onClose={onClose}
        title={t("userRecord.Make Review")}
        actionConfig={{
          type: "forward",
          onAction: handleMakeReview,
          confirmText: t("userRecord.Confirm Review"),
          confirmVariant: "default",
          isLoading: false, // disable button while loading
        }}
      />
      {loading && <Loader mode="inline" className="mt-2" showLabel={false} />}
    </>
  );
};

export default UnderReviewRecord;
