import { Button } from "@/shared/common/ui/button";

import { useNavigate } from "react-router-dom";
import { t } from "i18next";
import { RecordOfficerRecordsDto } from "@/record-management/dto/recordOfficer/recordOfficerRecordDto";
import { ReplyModal } from "@/record-management/common/ReplyModal";
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 { EllipsisVertical, Lock, Send, Unlock } from "lucide-react";
import { useState } from "react";
import { useOutgoingRecords } from "@/record-management/components/hooks/useOutgoingRecords";

import { useQueryClient } from "@tanstack/react-query";

interface OutgoingRecordActionsProps {
  rowData: RecordOfficerRecordsDto;
  pageIndex: number;
}

export function OutgoingRecordActions({
  rowData,
  pageIndex,
}: OutgoingRecordActionsProps) {
  console.log("rowData", rowData);
  const [isReplyOpen, setIsReplyOpen] = useState(false);
  const [isLockConfirmationOpen, setIsLockConfirmationOpen] = useState(false);
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { makeRecordLocked, isLocking } = useOutgoingRecords();
  const isLocked = rowData?.isLocked ?? false;

  const handleView = () => {
    if (rowData.id) {
      navigate(`/record-management/view/${rowData.id}/?page=${pageIndex}`);
    }
  };
  const handleLockRecord = () => {
    if (!rowData?.id) return;
    setIsLockConfirmationOpen(false);
    makeRecordLocked({
      recordId: rowData.id,
      isLocked: !isLocked,
    });
  };

  const refreshAfterReply = () => {
    queryClient.invalidateQueries({
      queryKey: ["record-instance", rowData.id],
    });
    queryClient.invalidateQueries({ queryKey: ["record", rowData.id] });
  };

  return (
    <>
      <div className="flex items-center justify-center gap-2">
        <Button variant={"viewDetail"} onClick={() => handleView()}>
          {t("userIncoming.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",
                  "Open actions menu",
                )}
              </span>
            </Button>
          </DropdownMenuTrigger>

          <DropdownMenuContent
            align="end"
            className="w-[200px]"
            onCloseAutoFocus={(e) => e.preventDefault()}
          >
            <DropdownMenuLabel>
              {t("userIncomingretun.Actions", "Actions")}
            </DropdownMenuLabel>

            <DropdownMenuItem
              className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
              disabled={isLocking}
              onSelect={() => setIsLockConfirmationOpen(true)}
            >
              {isLocked ? (
                <Unlock className="mr-2 h-4 w-4 transition-colors duration-200" />
              ) : (
                <Lock className="mr-2 h-4 w-4 transition-colors duration-200" />
              )}
              {isLocked
                ? t("userIncoming.UnlockRecord", "Unlock Record")
                : t("userIncoming.LockRecord", "Lock Record")}
            </DropdownMenuItem>

            {rowData.recordTypeKey === "external" && (
              <DropdownMenuItem
                className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                onClick={() => setIsReplyOpen(true)}
              >
                <Send className="mr-2 h-4 w-4 transition-colors duration-200" />
                {t("common.addReply", "Add Reply")}
              </DropdownMenuItem>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      <AlertDialog
        open={isLockConfirmationOpen}
        onOpenChange={setIsLockConfirmationOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {isLocked
                ? t("userIncoming.ConfirmUnlockRecord", "Unlock record?")
                : t("userIncoming.ConfirmLockRecord", "Lock record?")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {isLocked
                ? t(
                    "userIncoming.ConfirmUnlockRecordDescription",
                    "Are you sure you want to unlock this record?",
                  )
                : t(
                    "userIncoming.ConfirmLockRecordDescription",
                    "Are you sure you want to lock this record?",
                  )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isLocking}>
              {t("common.Cancel", "Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              disabled={isLocking}
              onClick={handleLockRecord}
            >
              {isLocked
                ? t("userIncoming.UnlockRecord", "Unlock Record")
                : t("userIncoming.LockRecord", "Lock Record")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {rowData.id && (
        <ReplyModal
          isOpen={isReplyOpen}
          onClose={() => setIsReplyOpen(false)}
          recordId={rowData.id}
          onSuccess={refreshAfterReply}
        />
      )}
    </>
  );
}
