import {
  SearchCheck,
  Forward,
  EllipsisVertical,
  Activity,
  FileText,
  X,
  SquareX,
  Repeat2,
  MessageSquareMore,
  Lock, // Added lock icon
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { Button } from "@/shared/common/ui/button";
import { useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";

import { toast } from "sonner";

import AcceptIncomingRecord from "./AcceptIncoming";
import RejectIncomingRecord from "./RejectIncoming";
import ParentContainer from "@/record-management/components/recordOfficer/recordDetails/ParentAssignementContainer";
import { useTranslation } from "react-i18next";

import { useQueryClient } from "@tanstack/react-query";
import { hasSeen } from "@/record-management/services/api/incomingRecordService";
import { IncomingLetterItem } from "@/record-management/dto/IncomingRecords/incomingTasksDto";
import AssignRecordV2 from "./AssignRecordV2";
import useCanAssignRecord from "@/record-management/components/hooks/useCanAssignRecord";

import IncomingInstanceDetail from "../IncomingInstanceDetail";

export interface DisplayRecordDto {
  id: string;
  recordTypeKey: string;
  subject: string;
  createdAt: string;
  referenceNumber?: string;
  pageIndex?: number;
}

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

const getLatestRemarkAt = (
  latestRemarkAt?: string | null,
  childAssignments?: { latestRemarkAt?: string | null }[],
) => {
  const remarkDates = [
    latestRemarkAt,
    ...(childAssignments?.map((child) => child.latestRemarkAt) ?? []),
  ].filter(Boolean) as string[];

  return remarkDates.reduce<string | null>((latest, current) => {
    if (!latest) return current;

    const latestTime = new Date(latest).getTime();
    const currentTime = new Date(current).getTime();

    if (Number.isNaN(latestTime) || Number.isNaN(currentTime)) {
      return latest;
    }

    return currentTime > latestTime ? current : latest;
  }, null);
};

const TaskUpdateHint = ({
  latestRemarkAt,
  remarkLabel,
}: {
  latestRemarkAt?: string | null;
  remarkLabel: string;
}) => {
  const isRemark = !!latestRemarkAt;

  return (
    isRemark && (
      <span
        className={`mt-1 inline-flex justify-center rounded-full border px-2 py-0.5 text-[11px] font-medium ${
          isRemark
            ? "border-amber-200 bg-amber-50 text-amber-700"
            : "border-blue-200 bg-blue-50 text-blue-700"
        }`}>
        {remarkLabel}
      </span>
    )
  );
};

// Internal Incoming Actions component
export function InternalIncomingRecordActionsV2({
  rowData,
  refetchTable,
  isSelf,
  pageIndex,
  fromTable,
  isDropdownOpen,
  onDropdownOpenChange,
  dropdownId,
  onAssign,
}: {
  rowData?: IncomingLetterItem;
  refetchTable?: () => void;
  isSecretary?: boolean;
  isSelf?: boolean;
  pageIndex?: number;
  fromTable: boolean;
  isLocked?: boolean; // NEW
  isDropdownOpen?: boolean;
  onDropdownOpenChange?: (open: boolean) => void;
  dropdownId?: string;
  onAssign?: (rowData: IncomingLetterItem) => void;
}) {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [showRemarkDialog, setShowRemarkDialog] = useState(false);
  const [showAcceptDialog, setShowAcceptDialog] = useState(false);
  const [showRejectDialog, setShowRejectDialog] = useState(false);
  const [isPanelOpen, setIsPanelOpen] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<DisplayRecordDto | null>(
    null,
  );
  const secretaryView = isSelf ? "" : "parent";
  const queryClient = useQueryClient();

  const handleSeen = useCallback(async () => {
    if (!rowData?.id) throw new Error("Invalid Record ID");
    // await hasSeen(rowData?.id);
    if (refetchTable) await refetchTable();
    queryClient.invalidateQueries({ queryKey: ["record-incoming"] });
    queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
    queryClient.invalidateQueries({ queryKey: ["incoming-instances"] });
    queryClient.invalidateQueries({ queryKey: ["incoming-instances-parent"] });
    queryClient.invalidateQueries({ queryKey: ["external-incoming"] });
    queryClient.invalidateQueries({ queryKey: ["external-incoming-parent"] });
    queryClient.invalidateQueries({ queryKey: ["approvalRecord"] });
  }, [queryClient, refetchTable, rowData?.id]);

  const handleViewDetails = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    
    const lastIncomingInstance = rowData?.incomingInstances?.[0];
    const baseUrl = `/record-management/viewIncoming/internal/${lastIncomingInstance?.id}/?page=${pageIndex}`;
    const url = secretaryView === "parent" ? `${baseUrl}&view=parent` : baseUrl;

    navigate(url, {
      state: {
        actionRowData: rowData,
      },
    });
    await handleSeen();
  };

  const handleReply = (e: PreventableEvent) => {
    e.preventDefault();
    navigate(`/record-management/userRecords/addUserRecord/${rowData?.id}`);
  };

  const openAssignDialog = (e: PreventableEvent) => {
    e.preventDefault();
    if (fromTable && onAssign && rowData) {
      onAssign(rowData);
      onDropdownOpenChange?.(false);
      return;
    }
    
    setShowAssignModal(true);
  };
  const openRemarkDialog = (e: PreventableEvent) => {
    e.preventDefault();
    
    setShowRemarkDialog(true);
  };
  const openAcceptDialog = (e: PreventableEvent) => {
    e.preventDefault();
    
    setShowAcceptDialog(true);
  };
  const openRejectDialog = (e: PreventableEvent) => {
    e.preventDefault();
    
    setShowRejectDialog(true);
  };

  const isDelegation = Boolean(rowData?.isDelegation);
  const lastInstance = rowData?.incomingInstances?.[0];
  const latestRemarkAt = getLatestRemarkAt(
    lastInstance?.latestRemarkAt,
    lastInstance?.childAssignments,
  );
  const status = lastInstance?.status;
  const isLocked = rowData?.isLocked ?? false;
  const normalizedStatus = (status ?? "").toString().trim().toLowerCase();
  const isRejected = normalizedStatus === "rejected";
  const isInProgress =
    normalizedStatus === "draft" || normalizedStatus === "in_progress";
  const isReassigned = normalizedStatus === "re_assigned";
  const isAcceptable = !isRejected && isInProgress;
  const { canAssignRecord } = useCanAssignRecord();

  const isAssignable = !isDelegation && canAssignRecord;
  const isRejectable = !isDelegation && !isRejected && isInProgress;
  const isRemarkable = isReassigned;
  const isReplyable = !isRejected && isInProgress && !isDelegation;
  const shouldShowMenu = true;

  const hasInlineActions =
    shouldShowMenu &&
    isSelf &&
    (isAcceptable ||
      isAssignable ||
      isReplyable ||
      isRejectable ||
      isRemarkable);

  const effectiveIsAcceptable = isAcceptable && !isLocked;
  const effectiveIsAssignable = isAssignable && !isLocked;
  const effectiveIsRejectable = isRejectable && !isLocked;
  const effectiveIsReplyable = isReplyable && !isLocked;
  const effectiveIsRemarkable = isRemarkable && !isLocked;
  const effectiveHasInlineActions = hasInlineActions && !isLocked;
  const effectiveShouldShowMenu = shouldShowMenu && isSelf && !isLocked;

  return (
    <>
      {/* =========================
        TABLE VIEW
      ========================== */}
      {fromTable ? (
        <div className="flex flex-wrap items-center gap-1 sm:gap-2">
          {/* View Detail - ALLOWED even when locked */}
          <div className="flex min-w-[110px] flex-col items-start">
            <Button
              variant="viewDetail"
              className="w-full"
              onClick={handleViewDetails}>
              {t("userIncoming.View Detail")}
            </Button>
            <TaskUpdateHint
              latestRemarkAt={latestRemarkAt}
              remarkLabel={t("userIncoming.remarkAdded")}
            />
          </div>

          {/* NEW: Locked Badge */}
          {isLocked && (
            <div className="flex items-center gap-1.5 rounded-full border border-amber-200 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-700 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-400">
              <Lock className="h-3.5 w-3.5" />
              {t("userIncoming.Locked", "Locked")}
            </div>
          )}

          {/* Actions Dropdown - Hidden when locked */}
          {effectiveShouldShowMenu && (
            <DropdownMenu open={isDropdownOpen} onOpenChange={onDropdownOpenChange || (() => {})}>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  className="flex h-10 w-10 items-center justify-center p-0 data-[state=open]:bg-muted sm:h-8 sm:w-8">
                  <EllipsisVertical className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>

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

                {/* Assign */}
                {effectiveIsAssignable && (
                  <DropdownMenuItem
                    onSelect={openAssignDialog}
                    className="cursor-pointer hover:!text-[#17a397]">
                    <Forward className="mr-2 h-4 w-4" />
                    {t("userIncoming.Assign")}
                  </DropdownMenuItem>
                )}

                {/* Accept */}
                {effectiveIsAcceptable && (
                  <DropdownMenuItem
                    onSelect={openAcceptDialog}
                    className="cursor-pointer hover:!text-[#17a397]">
                    <SearchCheck className="mr-2 h-4 w-4" />
                    {t("userIncoming.Accept")}
                  </DropdownMenuItem>
                )}

                {/* Reply */}
                {effectiveIsReplyable && (
                  <DropdownMenuItem
                    onSelect={handleReply}
                    className="cursor-pointer hover:!text-[#17a397]">
                    <Repeat2 className="mr-2 h-4 w-4" />
                    {t("userIncoming.reply")}
                  </DropdownMenuItem>
                )}

                {/* Reject */}
                {effectiveIsRejectable && (
                  <DropdownMenuItem
                    onSelect={openRejectDialog}
                    className="cursor-pointer hover:!text-[#ff8787]">
                    <SquareX className="mr-2 h-4 w-4" />
                    {t("userIncoming.Reject")}
                  </DropdownMenuItem>
                )}

                {/* Remark */}
              </DropdownMenuContent>
            </DropdownMenu>
          )}

          {/* Activity / Parent Container Trigger - ALLOWED even when locked */}
          <Button
            className="h-12 w-12 bg-transparent p-0 text-[#17a397] hover:bg-transparent hover:text-[#17a397] sm:h-10 sm:w-10"
            onClick={(e) => {
              e.preventDefault();
              if (!rowData) return;
              setSelectedRecord({
                id: rowData.id,
                recordTypeKey: rowData.recordTypeKey,
                subject: rowData.content[0]?.subject ?? "",
                createdAt: new Date().toISOString(),
                referenceNumber: "N/A",
              });
              setIsPanelOpen(true);
            }}>
            <Activity />
          </Button>
          <IncomingInstanceDetail
            instanceId={
              (rowData?.incomingInstances?.[0]?.id as string) ||
              (rowData?.id as string)
            }
            rowData={rowData}
          />
          {/* =========================
            SIDE PANEL
          ========================== */}
          {isPanelOpen && (
            <>
              <div
                className="fixed inset-0 z-40 bg-black/40 backdrop-blur-sm"
                onClick={() => setIsPanelOpen(false)}
              />
              <div
                className={`fixed right-0 top-0 z-50 flex h-full w-full transform flex-col border-l border-gray-200 bg-white shadow-2xl transition-transform duration-300 sm:w-[600px] lg:w-[720px] dark:border-gray-800 dark:bg-gray-900 ${
                  isPanelOpen ? "translate-x-0" : "translate-x-full"
                }`}>
                <div className="flex items-center justify-between border-b border-gray-200 bg-gradient-to-r from-green-50 to-emerald-50/50 px-5 py-4 dark:border-gray-800">
                  <div className="flex items-center gap-3">
                    <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-green-100">
                      <FileText className="h-5 w-5 text-green-600" />
                    </div>
                    <h2 className="text-lg font-semibold">
                      {t("userIncoming.View Detail")}
                    </h2>
                  </div>
                  <button
                    className="flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 hover:bg-red-50 hover:text-red-600"
                    onClick={() => setIsPanelOpen(false)}>
                    <X className="h-5 w-5" />
                  </button>
                </div>
                <div className="flex-1 overflow-y-auto bg-gray-50/50 dark:bg-gray-900">
                  {selectedRecord ? (
                    <div className="p-4 sm:p-5">
                      <ParentContainer
                        recordId={selectedRecord.id}
                        recordTitle=""
                        recordType={selectedRecord.recordTypeKey}
                        subject={selectedRecord.subject}
                        createdDate={selectedRecord.createdAt}
                        referenceNumber={selectedRecord.referenceNumber}
                      />
                    </div>
                  ) : (
                    <div className="flex h-full flex-col items-center justify-center text-gray-400">
                      <FileText className="mb-3 h-12 w-12 opacity-40" />
                      <p className="text-sm font-medium">No record selected.</p>
                    </div>
                  )}
                </div>
              </div>
            </>
          )}
        </div>
      ) : (
        /* =========================
          INLINE ACTIONS
        ========================== */
        <div>
          {isLocked ? (
            /* NEW: Locked state for inline view */
            <div className="flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-2.5 text-sm font-medium text-amber-700 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-400">
              <Lock className="h-4 w-4" />
              {t("userIncoming.RecordLocked", "This record is locked")}
            </div>
          ) : effectiveHasInlineActions ? (
            <div className="flex flex-wrap gap-5">
              {/* Assign */}
              {effectiveIsAssignable && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={openAssignDialog}
                  className="h-9 rounded-full border-blue-200 bg-gradient-to-r from-blue-50 to-indigo-50 px-4 shadow-sm transition-all duration-300 hover:border-blue-300 hover:from-blue-100 hover:to-indigo-100 dark:border-blue-800 dark:from-blue-950/50 dark:to-indigo-950/50 dark:hover:border-blue-700 dark:hover:from-blue-900/50 dark:hover:to-indigo-900/50 dark:text-blue-300">
                  <Forward className="mr-2 h-4 w-4 text-blue-600" />
                  {t("userIncoming.Assign")}
                </Button>
              )}

              {/* Accept */}
              {effectiveIsAcceptable && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={openAcceptDialog}
                  className="h-9 rounded-full border-emerald-200 bg-gradient-to-r from-emerald-50 to-green-50 px-4 shadow-sm transition-all duration-300 hover:border-emerald-300 hover:from-emerald-100 hover:to-green-100 dark:border-emerald-800 dark:from-emerald-950/50 dark:to-green-950/50 dark:hover:border-emerald-700 dark:hover:from-emerald-900/50 dark:hover:to-green-900/50 dark:text-emerald-300">
                  <SearchCheck className="mr-2 h-4 w-4 text-emerald-600" />
                  {t("userIncoming.Accept")}
                </Button>
              )}

              {/* Reply */}
              {effectiveIsReplyable && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleReply}
                  className="h-9 rounded-full border-amber-200 bg-gradient-to-r from-amber-50 to-orange-50 px-4 shadow-sm transition-all duration-300 hover:border-amber-300 hover:from-amber-100 hover:to-orange-100 dark:border-amber-800 dark:from-amber-950/50 dark:to-orange-950/50 dark:hover:border-amber-700 dark:hover:from-amber-900/50 dark:hover:to-orange-900/50 dark:text-amber-300">
                  <Repeat2 className="mr-2 h-4 w-4 text-amber-600" />
                  {t("userIncoming.reply")}
                </Button>
              )}

              {/* Reject */}
              {effectiveIsRejectable && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={openRejectDialog}
                  className="h-9 rounded-full border-rose-200 bg-gradient-to-r from-rose-50 to-red-50 px-4 shadow-sm transition-all duration-300 hover:border-rose-300 hover:from-rose-100 hover:to-red-100 dark:border-rose-800 dark:from-rose-950/50 dark:to-red-950/50 dark:hover:border-rose-700 dark:hover:from-rose-900/50 dark:hover:to-red-900/50 dark:text-rose-300">
                  <SquareX className="mr-2 h-4 w-4 text-rose-600" />
                  {t("userIncoming.Reject")}
                </Button>
              )}

              {/* Remark */}
              <IncomingInstanceDetail
                instanceId={
                  (rowData?.incomingInstances?.[0]?.id as string) ||
                  (rowData?.id as string)
                }
                rowData={rowData}
                fromTable={false}
              />
            </div>
          ) : (
            <p className="italic text-sm text-gray-500 dark:text-gray-400">
              {t("userIncoming.noActionsAvailable", {
                defaultValue: "No actions available for this record.",
              })}
            </p>
          )}
        </div>
      )}

      {/* =========================
        REMARK MODAL
      ========================== */}

      {/* =========================
        ASSIGN MODAL
      ========================== */}
      {showAssignModal && !isLocked && (
        <AssignRecordV2
          record={rowData as IncomingLetterItem}
          isTable={fromTable}
          isOpen
          onClose={() => {
            setShowAssignModal(false);
            refetchTable?.();
            queryClient.invalidateQueries({
              queryKey: ["incoming-instances"],
            });
            queryClient.invalidateQueries({
              queryKey: ["dashbordReport"],
            });
          }}
          onSuccess={() => {
            toast.success(t("msg.successassign"));
            setShowAssignModal(false);
            refetchTable?.();
            queryClient.invalidateQueries({ queryKey: ["incoming-instances"] });
            queryClient.invalidateQueries({
              queryKey: ["incoming-instances/v2"],
            });
            queryClient.invalidateQueries({
              queryKey: ["dashbordReport"],
            });
          }}
        />
      )}

      {/* =========================
        ACCEPT MODAL
      ========================== */}
      {showAcceptDialog && !isLocked && (
        <AcceptIncomingRecord
          open={showAcceptDialog}
          incomingInstanceId={rowData?.incomingInstances?.[0]?.id as string}
          onClose={() => {
            setShowAcceptDialog(false);
            refetchTable?.();
            queryClient.invalidateQueries({
              queryKey: ["incoming-instances"],
            });
            queryClient.invalidateQueries({
              queryKey: ["incoming-instances/v2"],
            });
            queryClient.invalidateQueries({
              queryKey: ["dashbordReport"],
            });
          }}
        />
      )}

      {/* =========================
        REJECT MODAL
      ========================== */}
      {showRejectDialog && !isLocked && (
        <RejectIncomingRecord
          open={showRejectDialog}
          incomingInstanceId={rowData?.incomingInstances?.[0]?.id as string}
          onClose={() => {
            setShowRejectDialog(false);
            refetchTable?.();
            queryClient.invalidateQueries({ queryKey: ["incoming-instances"] });
            queryClient.invalidateQueries({
              queryKey: ["incoming-instances/v2"],
            });
            queryClient.invalidateQueries({
              queryKey: ["dashbordReport"],
            });
          }}
          onSuccess={() => {
            if (!fromTable) {
              navigate(-1);
            }
          }}
        />
      )}
    </>
  );
}
