import { useCallback } from "react";
import { toast } from "sonner";
import { useApprovalTasks } from "../../hooks/useApprovalTasks";
import EnhancedDynamicModal from "@/record-management/common/EnhancedDynamicModal";

import { t } from "i18next";
import { AdjustmentDto } from "@/record-management/dto/userRecords/userRecordsDto";
import { PendingApprovalDto } from "@/record-management/dto/approval/approvalRecordsDto";

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

const AcceptRecord: React.FC<AcceptRecordProps> = ({
  record,
  onSuccess,
  onClose,
}) => {
  const { refetch, acceptRecord } = useApprovalTasks(undefined);

  const handleAccept = useCallback(
    async (data: any) => {
      if (!record) throw new Error("Invalid record");

      const requestBody: AdjustmentDto = {
        instanceId: record.id,
        action: "approve",
        comment: data.remarks || "No Comment/አስተያየት የለም", // get from passed data
      };

      await acceptRecord(requestBody);
      await refetch();

      toast.success(t("ApprovalPage.Record accepted successfully"));
      onSuccess();
    },
    [record, acceptRecord, refetch, onSuccess]
  );

  return (
    <EnhancedDynamicModal
      open={true}
      onClose={onClose}
      title={t("ApprovalPage.Accept Record")}
      actionConfig={{
        type: "accept",
        onAction: handleAccept,
        confirmText: t("ApprovalPage.confirmApprove"),
        confirmVariant: "default",
      }}
      formConfig={{
        fields: [
          {
            type: "textarea",
            name: "remarks",
            label: t("ApprovalPage.Remarks"),
            placeholder: t("ApprovalPage.Remarks"),
            required: false,
          },
        ],
      }}
    />
  );
};

export default AcceptRecord;
