import { useState, useCallback } 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 RejectRecord: React.FC<AcceptRecordProps> = ({
  record,
  onSuccess,
  onClose,
}) => {
  const { refetch, rejectRecord } = useApprovalTasks();

  const handleReject = useCallback(
    async (data?: Record<string, any>) => {
      const requestBody = {
        instanceId: record.id,
        action: "reject",
        comment: data?.remarks || "No Comment/አስተያየት የለም",
        goBackTo: undefined,
      };

      if (!record) throw new Error("Invalid record");

      await rejectRecord(requestBody);
      await refetch();

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

  return (
    <EnhancedDynamicModal
      open={true}
      onClose={onClose}
      title={t("ApprovalPage.Reject Record")}
      actionConfig={{
        type: "reject",
        onAction: handleReject,
        confirmText: t("ApprovalPage.confirmRejection"),
        confirmVariant: "default",
      }}
      formConfig={{
        fields: [
          {
            type: "textarea",
            name: "remarks",
            label: t("ApprovalPage.Remark"),
            placeholder: t("ApprovalPage.Remark"),
            required: false,
          },
        ],
      }}
    />
  );
};

export default RejectRecord;
