import React, { useState } from "react";
import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";
import { Button } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
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 { EllipsisVertical, Pencil, RotateCcw, Undo } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  useSendBackToInitiator,
  SendBackPayload,
} from "@/record-management/services/api/returnService";
import { useQueryClient } from "@tanstack/react-query";
import { useAuthUser } from "@/shared/hooks/useAuthUser";

interface UserRecordProps {
  rowData: RecordDto;
  pageIndex: number;
  canROReturn: boolean;
}

const PendingRecordsActions: React.FC<UserRecordProps> = ({
  rowData,
  pageIndex,
  canROReturn,
}) => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const { selectedPositionPermissionKeys } = useAuthUser();
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [returnComment, setReturnComment] = useState("");

  // Use your mutation hook here
  const mutation = useSendBackToInitiator();

  const handleViewDetails = () => {
    navigate(`/record-management/viewPending/${rowData.id}/?page=${pageIndex}`);
  };

  const handleReturnClick = () => {
    setReturnComment(""); // Reset comment when opening dialog
    setShowConfirmDialog(true);
  };

  const handleConfirmReturn = async () => {
    // Validate that comment is provided
    if (!returnComment.trim()) {
      toast.error(t("userIncomingretunretun.CommentRequired"));
      return;
    }

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

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

      // Invalidate queries to refresh the data
      queryClient.invalidateQueries({ queryKey: ["pendingRecords"] });
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });

      setShowConfirmDialog(false);
      setReturnComment(""); // Reset comment after successful return
    } catch {
      toast.error(t("userIncomingretun.FailedToReturnRecord"));
    }
  };

  return (
    <div className="flex gap-2">
      <Button variant={"viewDetail"} onClick={handleViewDetails}>
        {t("userIncomingretun.View Detail")}
      </Button>

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            className="flex h-8 w-8 p-0 data-[state=open]:bg-muted">
            <EllipsisVertical className="h-4 w-4" />
            <span className="sr-only">
              {t("userIncomingretun.Open actions menu")}
            </span>
          </Button>
        </DropdownMenuTrigger>

        <DropdownMenuContent
          align="end"
          className="w-[200px]"
          onCloseAutoFocus={(e) => e.preventDefault()}
          onInteractOutside={(e) => {
            const target = e.target as HTMLElement;
            if (target.closest('[role="dialog"]')) {
              e.preventDefault();
            }
          }}>
          <DropdownMenuLabel>
            {t("userIncomingretun.Actions")}
          </DropdownMenuLabel>

          {/* Convert Action */}
          <DropdownMenuItem
            className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
            onClick={() =>
              navigate(`/record-management/convert/${rowData?.id}`)
            }>
            <Pencil className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
            {t("convert.convertRecord")}
          </DropdownMenuItem>

          {/* Return Action */}
          {canROReturn && (
            <DropdownMenuItem
              className="cursor-pointer hover:!text-red-500 !bg-transparent !transition-colors duration-200"
              onClick={handleReturnClick}
              disabled={mutation.isPending} // disable while loading
            >
              <Undo className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
              {mutation.isPending
                ? t("userIncomingretun.returning")
                : t("userIncomingretun.return")}
            </DropdownMenuItem>
          )}
        </DropdownMenuContent>
      </DropdownMenu>

      {/* Confirmation Dialog */}
      <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>
    </div>
  );
};

export default PendingRecordsActions;
