"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 { Textarea } from "@/shared/common/ui/textarea";
import { t } from "i18next";
import { useState } from "react";
import { toast } from "sonner";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

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

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

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

    acceptIncoming(requestBody, {
      onSuccess: () => {
        toast.success(t("userIncoming.Record accepted successfully"));
        setIsLoading(false);
        onClose();
      },
      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 Acceptance')}</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <p>{t('userIncoming.Are you sure you want to accept this record?')}</p>
          <Textarea
            placeholder={t('userIncoming.Comment')}
            value={comment}
            onChange={(e) => setComment(e.target.value)}
          />
        </div>

        <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 AcceptIncomingRecord;
