import { useState, useCallback, useRef } from "react";
import { toast } from "sonner";
import { useApprovalTasks } from "../../hooks/useApprovalTasks";

import EnhancedDynamicModal from "@/record-management/common/EnhancedDynamicModal";
import { PendingApprovalDto } from "@/record-management/dto/approval/approvalRecordsDto";
import { t } from "i18next";

interface AcceptRecordProps {
  record: PendingApprovalDto;
  onSuccess: () => void;
  onClose: () => void;
}

const AdjustRecord: React.FC<AcceptRecordProps> = ({
  record,
  onSuccess,
  onClose,
}) => {
  const { refetch, adjustRecord } = useApprovalTasks();
  const [isSubmitting, setIsSubmitting] = useState(false);

  // handleAccept now receives the form data from the modal
  const handleAccept = useCallback(
    async (data?: Record<string, any>) => {
      if (!record) {
        toast.error("Invalid record");
        return;
      }

      const remarks = data?.remarks?.trim() ?? "";

      // Validate that remarks are not empty
      if (!remarks) {
        toast.error(t("ApprovalPage.remarkRequired", "Remark is required"));
        return;
      }

      setIsSubmitting(true);

      try {
        const requestBody = {
          instanceId: record.id,
          action: "send_back",
          comment: remarks,
          goBackTo: undefined,
        };

        await adjustRecord(requestBody);
        await refetch();

        toast.success(t("ApprovalPage.Record adjusted successfully"));
        onSuccess();
      } catch (error) {
        console.error("Failed to adjust record:", error);
        toast.error(
          t("ApprovalPage.adjustmentFailed", "Failed to adjust record"),
        );
      } finally {
        setIsSubmitting(false);
      }
    },
    [record, adjustRecord, refetch, onSuccess],
  );

  return (
    <EnhancedDynamicModal
      open={true}
      onClose={onClose}
      title={t("ApprovalPage.Adjust Record")}
      actionConfig={{
        type: "adjust",
        confirmText: t("ApprovalPage.confirmAdjustment"),
        confirmVariant: "default",
        onAction: handleAccept,
        disabled: isSubmitting,
      }}
      formConfig={{
        fields: [
          {
            type: "textarea",
            name: "remarks",
            label: t("ApprovalPage.Remark"),
            required: true,
            placeholder: t("ApprovalPage.Remark"),
          
            rules: {
              required: {
                value: true,
                message: t("ApprovalPage.remarkRequired", "Remark is required"),
              },
            },
          },
        ],
      }}
    />
  );
};

export default AdjustRecord;
