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

import { useTranslation } from "react-i18next";
import { useMyCollaborations } from "../hooks/useMyCollaborations";

interface ApproveCollaborationRecordProps {
  collaborationId: string;
  onSuccess: () => void;
  onClose: () => void;
}

const ApproveCollaborationRecord: React.FC<ApproveCollaborationRecordProps> = ({
  collaborationId,
  onSuccess,
  onClose,
}) => {
  const { signCollaboration, refetch, signStatus } = useMyCollaborations();

  const { t } = useTranslation();

  const handleApprove = useCallback(
    async (data: any) => {
      if (!collaborationId) {
        toast.error("Invalid record ID");
        return;
      }
      try {
        const remark = data.remarks;
        signCollaboration({
          payload: {
            collabId: collaborationId,
            signStatus: "signed",
            comment: remark || "No Comment/አስተያየት የለም",
          },
        }).then(() => {
          toast.success(t("userRecord.Record approved successfully!"));
          onSuccess();
        });
      } catch (error: any) {
        toast.error(error.message || t("userRecord.Failed to approve record."));
      }
    },
    [collaborationId, refetch, onSuccess]
  );
  return (
    <EnhancedDynamicModal
      open={true}
      onClose={onClose}
      title={t("userRecord.Approve Record")}
      formConfig={{
        fields: [
          {
            type: "textarea",
            name: "remarks",
            label: t("ApprovalPage.Remark"),
            placeholder: t("ApprovalPage.Remark"),
            required: false,
          },
        ],
      }}
      actionConfig={{
        type: "forward",
        onAction: handleApprove,
        confirmText: t("userRecord.Confirm Approve"),
        confirmVariant: "default",
        isLoading: signStatus.isLoading,
      }}
    />
  );
};

export default ApproveCollaborationRecord;
