import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { UserPlus, Edit, Trash, MoreVertical, Lock, Unlock } from "lucide-react";
import { useState } from "react";
// import AssigneRecord from "@/components/userIncoming/internalIncomingRecords/AssigneRecord";
import { useNavigate } from "react-router-dom";
import DeleteRecord from "./deleteRecord";
import { AssignRecordDto } from "@/record-management/dto/userRecords/usersDto";
import AssigneIncomingRecord from "./AssigneIncomingRecords";
import AssigneRecordExternal from "./AssigneIncomingExternalRecord";
import { toast } from "sonner";
import {
  CorrespondenceDto,
  IncomingRecordWrapperDto,
} from "@/record-management/dto/IncomingRecords/RecordOfficerIncoming";
import { useTranslation } from "react-i18next";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { lockRecord } from "@/record-management/services/api/userRecordService";

type PreventableEvent = {
  preventDefault: () => void;
};

interface IncomingRecordActionsProps {
  rowData: CorrespondenceDto | IncomingRecordWrapperDto;
  refetchTable?: () => void; // Optional callback to refetch table data
  shouldAddEditAction?: boolean;
  type?: string;
  pageIndex?: number;
  fromTable?: boolean;
  isDropdownOpen?: boolean;
  onDropdownOpenChange?: (open: boolean) => void;
  dropdownId?: string;
  recordTypeKey?: string;
  onAssignInternal?: (
    rowData: CorrespondenceDto | IncomingRecordWrapperDto,
  ) => void;
  onAssignExternal?: (
    rowData: CorrespondenceDto | IncomingRecordWrapperDto,
  ) => void;
}

export function IncomingRecordActions({
  rowData,
  refetchTable,
  shouldAddEditAction,
  type,
  pageIndex,
  fromTable = true,
  isDropdownOpen = false,
  onDropdownOpenChange,
  dropdownId = "",
  recordTypeKey: recordTypeKeyProp,
  onAssignInternal,
  onAssignExternal,
}: IncomingRecordActionsProps) {
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [showAssignModalExternal, setShowAssignModalExternal] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const recordId =
    "record" in rowData && rowData.record?.id ? rowData.record.id : rowData.id;
  const isLocked =
    ("record" in rowData && rowData.record?.isLocked !== undefined
      ? rowData.record.isLocked
      : rowData.isLocked) ?? false;

  const { mutate: updateRecordLock, isPending: isUpdatingLock } = useMutation({
    mutationFn: ({ id, value }: { id: string; value: boolean }) =>
      lockRecord(id, value),
    onSuccess: (_, variables) => {
      toast.success(
        variables.value
          ? t("userIncoming.RecordLocked", "Record locked")
          : t("userIncoming.RecordUnlocked", "Record unlocked"),
      );
      queryClient.invalidateQueries({ queryKey: ["external-record-incoming"] });
      queryClient.invalidateQueries({ queryKey: ["record-incoming"] });
      queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });
      refetchTable?.();
    },
    onError: () => {
      toast.error(t("userIncoming.LockUpdateFailed", "Failed to update lock"));
    },
  });

  const handleDetailView = () => {
    

    if (recordId) {
      navigate(
        `/record-management/viewIncoming/${recordId}/${type}/?page=${pageIndex}`,
        {
          state: { actionRowData: rowData },
        },
      );
    }
  };

  const handleAssign = (e: PreventableEvent) => {
    e.preventDefault();
    if (onAssignInternal) {
      onAssignInternal(rowData);
      onDropdownOpenChange?.(false);
      return;
    }
    setShowAssignModal(true);
  };
  const handleAssignExternal = (e: PreventableEvent) => {
    e.preventDefault();
    if (onAssignExternal) {
      onAssignExternal(rowData);
      onDropdownOpenChange?.(false);
      return;
    }
    setShowAssignModalExternal(true);
  };
  const handleEdit = (e: PreventableEvent) => {
    e.preventDefault();
    
    if (rowData.id) {
      navigate(`/record-management/editIncoming/${rowData.id}`);
    }
  };

  const handleDelete = (e: PreventableEvent) => {
    e.preventDefault();
    
    setShowDeleteDialog(true);
  };

  const handleToggleLock = (e: PreventableEvent) => {
    e.preventDefault();
    
    if (!recordId) return;
    updateRecordLock({ id: recordId, value: !isLocked });
  };

  const recordTypeKey =
    recordTypeKeyProp ??
    ("record" in rowData
      ? rowData.record?.recordTypeKey
      : (rowData as CorrespondenceDto & { recordTypeKey?: string })
          .recordTypeKey);
  const isCorrespondence = "statusKey" in rowData;
  const nonStatus =
    "nonSmartOfficeRecordStatus" in rowData &&
    rowData.nonSmartOfficeRecordStatus === "not_assigned";
  const canAssignExternal =
    recordTypeKey === "external" ||
    recordTypeKey === "non_smart_user" ||
    recordTypeKey === "external_non_smart_user";
  const canAssignInternal = isCorrespondence && !canAssignExternal;

  return (
    <>
      {fromTable ? (
        <>
          <Button variant={"viewDetail"} onClick={() => handleDetailView()}>
            {t("userIncoming.View Detail")}
          </Button>
          <DropdownMenu open={isDropdownOpen} onOpenChange={onDropdownOpenChange || (() => {})}>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" className="h-8 w-8 p-0 relative">
                <MoreVertical className="h-4 w-4" />
                <span className="sr-only">
                  {t("userIncoming.Open actions menu")}
                </span>
              </Button>
            </DropdownMenuTrigger>

            <DropdownMenuContent
              align="end"
              onCloseAutoFocus={(e) => e.preventDefault()}
              onInteractOutside={(e) => {
                const target = e.target as HTMLElement;
                if (!target.closest('[role="dialog"]')) {
                  
                }
              }}
            >
              <DropdownMenuLabel>{t("userRecord.Actions")}</DropdownMenuLabel>
              <DropdownMenuItem
                onSelect={handleToggleLock}
                disabled={isUpdatingLock}
                className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
              >
                {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" />
                )}
                <span>
                  {isLocked
                    ? t("userIncoming.UnlockRecord", "Unlock Record")
                    : t("userIncoming.LockRecord", "Lock Record")}
                </span>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              {canAssignInternal && (
                <>
                  <DropdownMenuItem
                    onSelect={handleAssign}
                    className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                  >
                    <UserPlus className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                    <span>{t("userIncoming.Assign")}</span>
                  </DropdownMenuItem>
                  {shouldAddEditAction && nonStatus && (
                    <>
                      <DropdownMenuItem
                        onSelect={handleEdit}
                        className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                      >
                        <Edit className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                        <span> {t("userRecord.Edit")}</span>
                      </DropdownMenuItem>

                      <DropdownMenuSeparator />
                      <DropdownMenuItem
                        onSelect={handleDelete}
                        className="text-red-600 cursor-pointer hover:!text-red-800 !bg-transparent !transition-colors duration-200"
                      >
                        <Trash className="mr-2 h-4 w-4 text-red-600 group-hover:text-white transition-colors duration-200" />
                        <span> {t("userRecord.Delete")}</span>
                      </DropdownMenuItem>
                    </>
                  )}
                </>
              )}
              {canAssignExternal && (
                <DropdownMenuItem
                  onSelect={handleAssignExternal}
                  className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                >
                  <UserPlus className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                  <span>{t("userIncoming.Assign")}</span>
                </DropdownMenuItem>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
        </>
      ) : (
        <div className="flex flex-wrap gap-2">
          {canAssignInternal && (
            <Button
              variant={getActionButtonVariant("Assign")}
              onClick={handleAssign}
            >
              <UserPlus className="h-4 w-4" />
              <span>
                {t("userIncoming.Assign")}
              </span>
            </Button>
          )}

          {canAssignExternal && (
            <Button
              variant={getActionButtonVariant("Assign")}
              onClick={handleAssignExternal}
            >
              <UserPlus className="h-4 w-4" />
              <span>
                {t("userIncoming.Assign")}
              </span>
            </Button>
          )}

          {shouldAddEditAction && nonStatus && (
            <Button
              variant={getActionButtonVariant("Edit")}
              onClick={handleEdit}
            >
              <Edit className="h-4 w-4" />
              <span>
                {t("userRecord.Edit")}
              </span>
            </Button>
          )}

          {shouldAddEditAction && nonStatus && (
            <Button
              variant={getActionButtonVariant("Delete")}
              onClick={handleDelete}
            >
              <Trash className="h-4 w-4" />
              <span>
                {t("userRecord.Delete")}
              </span>
            </Button>
          )}

          <Button
            variant={isLocked ? "outline" : getActionButtonVariant("Edit")}
            onClick={handleToggleLock}
            disabled={isUpdatingLock}
          >
            {isLocked ? (
              <Unlock className="h-4 w-4" />
            ) : (
              <Lock className="h-4 w-4" />
            )}
            <span>
              {isLocked
                ? t("userIncoming.UnlockRecord", "Unlock Record")
                : t("userIncoming.LockRecord", "Lock Record")}
            </span>
          </Button>
        </div>
      )}

      {showAssignModal && (
        <AssigneIncomingRecord
          record={rowData as unknown as AssignRecordDto}
          onClose={() => {
            setShowAssignModal(false);
            onDropdownOpenChange?.(false);
            if (refetchTable) {
              refetchTable();
            }
          }}
          onSuccess={() => {
            toast.success(t("msg.successassign"));
            setShowAssignModal(false);
            queryClient.invalidateQueries({
              queryKey: ["external-record-incoming"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });
          }}
          isOpen={true}
        />
      )}
      {showAssignModalExternal && (
        <AssigneRecordExternal
          record={rowData as unknown as AssignRecordDto}
          onClose={() => {
            setShowAssignModalExternal(false);
            onDropdownOpenChange?.(false);
            if (refetchTable) {
              refetchTable();
            }
          }}
          onSuccess={() => {
            toast.success(t("msg.successassign"));
            queryClient.invalidateQueries({
              queryKey: ["record-incoming"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });
            setShowAssignModalExternal(false);
            if (refetchTable) {
              refetchTable();
            }
          }}
          isOpen={true}
        />
      )}
      {showDeleteDialog && (
        <DeleteRecord
          recordId={(rowData?.id as string) || "0"}
          onSuccess={() => {
            setShowDeleteDialog(false);
            queryClient.invalidateQueries({
              queryKey: ["external-record-incoming"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });
            if (refetchTable) {
              refetchTable(); // Call the refetch function if provided
            }
          }}
          onClose={() => {
            setShowDeleteDialog(false);
            if (refetchTable) {
              refetchTable();
            }
          }}
        />
      )}
    </>
  );
}
