import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Pencil, Undo } from "lucide-react";

import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { Textarea } from "@/shared/common/ui/textarea";
import { Label } from "@/shared/common/ui/label";
import {
  useSendBackToInitiator,
  SendBackPayload,
} from "@/record-management/services/api/returnService";
import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";

interface PendingRecordDetailActionsProps {
  recordId: string;
  canROReturn: boolean;
  backToTable: string;
}

const PendingRecordDetailActions = ({
  recordId,
  canROReturn,
  backToTable,
}: PendingRecordDetailActionsProps) => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const mutation = useSendBackToInitiator();

  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [returnComment, setReturnComment] = useState("");

  const handleConvert = () => {
    navigate(`/record-management/convert/${recordId}`);
  };

  const handleReturnClick = () => {
    setReturnComment("");
    setShowConfirmDialog(true);
  };

  const handleConfirmReturn = async () => {
    if (!returnComment.trim()) {
      toast.error(t("userIncomingretunretun.CommentRequired"));
      return;
    }

    const payload: SendBackPayload = {
      recordId,
      action: "send_back",
      comment: returnComment.trim(),
    };

    try {
      await mutation.mutateAsync(payload);
      toast.success(t("userIncomingretun.RecordReturnedSuccessfully"));

      queryClient.invalidateQueries({ queryKey: ["pendingRecords"] });
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });

      setShowConfirmDialog(false);
      setReturnComment("");
      navigate(backToTable);
    } catch {
      toast.error(t("userIncomingretun.FailedToReturnRecord"));
    }
  };

  return (
    <>
      <div className="flex flex-wrap items-center gap-2">
        <Button
          variant={getActionButtonVariant("Edit")}
          onClick={handleConvert}
        >
          <Pencil className="h-4 w-4" />
          <span>{t("convert.convertRecord")}</span>
        </Button>

        {canROReturn && (
          <Button
            variant={getActionButtonVariant("Return")}
            onClick={handleReturnClick}
            disabled={mutation.isPending}
          >
            <Undo className="h-4 w-4" />
            <span>{mutation.isPending
              ? t("userIncomingretun.returning")
              : t("userIncomingretun.return")}</span>
          </Button>
        )}
      </div>

      <AlertDialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <AlertDialogContent className="max-w-md">
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("userIncomingretun.conformReturn")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(
                "userIncomingretun.Please provide a reason for returning this record.",
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>

          <div className="space-y-2">
            <Label htmlFor="return-comment" className="text-sm font-medium">
              {t("userIncomingretun.ReturnComment")} *
            </Label>
            <Textarea
              id="return-comment"
              placeholder={t("userIncomingretun.EnterReturnReason")}
              value={returnComment}
              onChange={(e) => setReturnComment(e.target.value)}
              rows={3}
              className="resize-none"
            />
            {!returnComment.trim() && (
              <p className="text-sm text-destructive">
                {t("userIncomingretun.CommentRequired")}
              </p>
            )}
          </div>

          <AlertDialogFooter>
            <AlertDialogCancel
              onClick={() => {
                setShowConfirmDialog(false);
                setReturnComment("");
              }}
            >
              {t("common.Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmReturn}
              disabled={mutation.isPending || !returnComment.trim()}
            >
              {mutation.isPending
                ? t("userIncomingretun.returing")
                : t("userIncomingretun.return")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default PendingRecordDetailActions;

// Helper to satisfy unused-import linting if needed elsewhere.
export type { RecordDto };
