"use client";

import { useAssignTasks } from "@/record-management/components/hooks/useAssignTasks";
import { Button } from "@/shared/common/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { useState } from "react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { Textarea } from "@/shared/common/ui/textarea";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

const RejectIncomingRecord: React.FC<{
  open: boolean;
  onClose: () => void;
  incomingInstanceId: string;
  onSuccess?: () => void;
}> = ({ open, onClose, incomingInstanceId, onSuccess }) => {
  const [isLoading, setIsLoading] = useState(false);
  const [comment, setComment] = useState("");
  const { acceptIncoming } = useAssignTasks();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const handleConfirmClick = async () => {
    setIsLoading(true);

    const requestBody = {
      incomingInstanceId: incomingInstanceId,
      status: "rejected",
      comment: comment,
    };

    acceptIncoming(requestBody, {
      onSuccess: () => {
        toast.success(t("userIncoming.Record rejected successfully"));
        setIsLoading(false);
        onClose();
        onSuccess?.();
      },
      onError: (error) => {
        handleError(error);
        setIsLoading(false);
      },
    });
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(isOpen) => {
        if (!isOpen) onClose(); // Only call onClose when dialog is closing
      }}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t("userIncoming.Confirm")}</DialogTitle>
        </DialogHeader>
        <p>{t("userIncoming.Are you sure you want to reject this record?")}</p>
        <Textarea
          placeholder={t("userIncoming.Comment")}
          value={comment}
          onChange={(e) => setComment(e.target.value)}
        />
        <DialogFooter className="flex gap-2">
          <Button variant="outline" onClick={onClose} disabled={isLoading}>
            {t("userIncoming.Cancel")}
          </Button>
          <Button
            onClick={handleConfirmClick}
            disabled={isLoading}
            className="bg-primary-600 hover:bg-primary-700">
            {isLoading
              ? t("userIncoming.Processing...")
              : t("userIncoming.Confirm")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default RejectIncomingRecord;
