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, getActionButtonVariant } from "@/shared/common/ui/button";
import { useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";

import AssigneRecord from "./AssigneRecord";
import useCanAssignRecord from "@/record-management/components/hooks/useCanAssignRecord";
import { AssignRecordDto } from "@/record-management/dto/userRecords/usersDto";
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 { AssignedRecordDto } from "@/record-management/dto/IncomingRecords/taskDto";
import { useQueryClient } from "@tanstack/react-query";
import { hasSeen } from "@/record-management/services/api/incomingRecordService";
import RemarkCreationDialog from "../remarkCreationCard";
import IncomingInstanceDetail from "../IncomingInstanceDetail";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { FaSitemap } from "react-icons/fa";

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 InternalIncomingRecordActions({
  rowData,
  refetchTable,
  isSelf,
  pageIndex,
  fromTable,
  isDropdownOpen = false,
  onDropdownOpenChange,
  dropdownId = "",
}: {
  rowData?: AssignedRecordDto;
  refetchTable?: () => void;
  isSecretary?: boolean;
  isSelf?: boolean;
  pageIndex?: number;
  fromTable: boolean;
  isLocked?: boolean; // NEW
  isDropdownOpen?: boolean;
  onDropdownOpenChange?: (open: boolean) => void;
  dropdownId?: string;
}) {
  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 openRemarkDialog = (e: PreventableEvent) => {
    e.preventDefault();
    
    setShowRemarkDialog(true);
  };

  const handleViewDetails = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    
    const baseUrl = `/record-management/viewIncoming/internal/${rowData?.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();
    
    setShowAssignModal(true);
  };

  const openAcceptDialog = (e: PreventableEvent) => {
    e.preventDefault();
    
    setShowAcceptDialog(true);
  };

  const openRejectDialog = (e: PreventableEvent) => {
    e.preventDefault();
    
    setShowRejectDialog(true);
  };

  const isDelegation = Boolean(rowData?.record?.isDelegation);
  const status = rowData?.status;
  const latestRemarkAt = getLatestRemarkAt(
    rowData?.latestRemarkAt,
    rowData?.childAssignments,
  );
  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 { canAssignRecord } = useCanAssignRecord();

  const isAcceptable = !isRejected && isInProgress;
  const isAssignable = !isDelegation && canAssignRecord;
  const isRejectable = !isDelegation && !isRejected && isInProgress;
  const isRemarkable = isReassigned;
  const isReplyable =
    !isRejected &&
    (normalizedStatus === "draft" || normalizedStatus === "in_progress") &&
    !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 (
    <>
      {fromTable ? (
        <div className="flex flex-wrap gap-1 sm:gap-2 items-center">
          {/* View Detail Button - ALLOWED even when locked */}
          <div className="flex min-w-[110px] flex-col items-start">
            <Button
              variant="viewDetail"
              className="w-full"
              onClick={(e) => handleViewDetails(e)}>
              {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>
          )}

          {/* Dropdown Menu - Hidden when locked */}
          {effectiveShouldShowMenu && (
            <DropdownMenu open={isDropdownOpen} onOpenChange={onDropdownOpenChange || (() => {})}>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  className="flex h-10 w-10 sm:h-8 sm:w-8 p-0 items-center justify-center data-[state=open]:bg-muted"
                  aria-haspopup="menu"
                  aria-expanded={isDropdownOpen}>
                  <EllipsisVertical className="h-4 w-4" />
                  <span className="sr-only">
                    {t("userIncoming.Open actions menu")}
                  </span>
                </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>

                <>
                  {effectiveIsAcceptable && (
                    <DropdownMenuItem
                      onSelect={openAcceptDialog}
                      className="cursor-pointer hover:!text-[#17a397] !bg-transparent transition-colors duration-200">
                      <SearchCheck className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                      {t("userIncoming.Accept")}
                    </DropdownMenuItem>
                  )}
                  {effectiveIsAssignable && (
                    <DropdownMenuItem
                      onSelect={openAssignDialog}
                      className="cursor-pointer hover:!text-[#17a397] !bg-transparent transition-colors duration-200">
                      <Forward className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                      {t("userIncoming.Assign")}
                    </DropdownMenuItem>
                  )}
                  {effectiveIsReplyable && (
                    <DropdownMenuItem
                      onSelect={handleReply}
                      className="cursor-pointer hover:!text-[#17a397] !bg-transparent transition-colors duration-200">
                      <Repeat2 className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                      {t("userIncoming.reply")}
                    </DropdownMenuItem>
                  )}
                  {effectiveIsRejectable && (
                    <DropdownMenuItem
                      onSelect={openRejectDialog}
                      className="cursor-pointer hover:!text-[#ff8787] !bg-transparent transition-colors duration-200">
                      <SquareX className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                      {t("userIncoming.Reject")}
                    </DropdownMenuItem>
                  )}
                </>
              </DropdownMenuContent>
            </DropdownMenu>
          )}

          {/* Activity Button - ALLOWED even when locked */}
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="
          h-9 w-9 rounded-lg
          text-muted-foreground
          hover:bg-primary
      hover:text-gray-100
          transition-all duration-200
        "
                  onClick={(e) => {
                    e.preventDefault();

                    const record = rowData?.record;

                    if (record) {
                      setSelectedRecord({
                        id: record.id,
                        recordTypeKey: record.recordTypeKey,
                        subject: record.content[0]?.subject ?? "",
                        createdAt: new Date().toISOString(),
                        referenceNumber: "N/A",
                      });

                      setIsPanelOpen(true);
                    }
                  }}
                  aria-label={t("setting.viewWF")}>
                  <FaSitemap className="h-4 w-4" />
                </Button>
              </TooltipTrigger>

              <TooltipContent side="top">
                <p>{t("setting.viewWF")}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
          <IncomingInstanceDetail
            instanceId={rowData?.id as string}
            rowData={rowData}
          />
          {/* Backdrop and Slide Panel */}
          {isPanelOpen && (
            <>
              <div
                className="fixed inset-0 z-40 bg-black/40 dark:bg-black/60 backdrop-blur-sm transition-opacity duration-300"
                onClick={() => setIsPanelOpen(false)}
              />

              <div
                className={`fixed top-0 right-0 z-50 h-full w-full sm:w-[600px] lg:w-[720px] bg-white dark:bg-gray-900 shadow-2xl border-l border-gray-200 dark:border-gray-800 transform transition-transform duration-300 ease-in-out flex flex-col ${
                  isPanelOpen ? "translate-x-0" : "translate-x-full"
                }`}
                onClick={(e) => e.stopPropagation()}>
                <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-800 bg-gradient-to-r from-primary-50 to-primary-50/50 dark:from-primary-900/20 dark:to-primary-900/10">
                  <div className="flex items-center gap-3">
                    <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary-100 dark:bg-primary-900/40">
                      <FileText className="h-5 w-5 text-primary-600 dark:text-primary-400" />
                    </div>
                    <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
                      {t("userIncoming.View Detail")}
                    </h2>
                  </div>
                  <button
                    className="flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 dark:text-gray-400 hover:bg-red-50 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 transition-colors"
                    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 flex-col items-center justify-center h-full text-gray-400 dark:text-gray-500">
                      <FileText className="h-12 w-12 mb-3 opacity-40" />
                      <p className="text-sm font-medium">No record selected.</p>
                    </div>
                  )}
                </div>
              </div>
            </>
          )}
        </div>
      ) : (
        <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">
              {effectiveIsAcceptable && (
                <Button
                  variant={getActionButtonVariant("Accept")}
                  onClick={openAcceptDialog}>
                  <SearchCheck className="h-4 w-4" />
                  <span>{t("userIncoming.Accept")}</span>
                </Button>
              )}

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

              {effectiveIsReplyable && (
                <Button
                  variant={getActionButtonVariant("Reply")}
                  onClick={handleReply}>
                  <Repeat2 className="h-4 w-4" />
                  <span>{t("userIncoming.reply")}</span>
                </Button>
              )}

              {effectiveIsRejectable && (
                <Button
                  variant={getActionButtonVariant("Reject")}
                  onClick={openRejectDialog}>
                  <SquareX className="h-4 w-4" />
                  <span>{t("userIncoming.Reject")}</span>
                </Button>
              )}

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

      {/* =========================
        REMARK MODAL
      ========================== */}
      {showRemarkDialog && !isLocked && (
        <RemarkCreationDialog
          open={showRemarkDialog}
          onClose={() => {
            setShowRemarkDialog(false);
            refetchTable?.();
            queryClient.invalidateQueries({
              queryKey: ["incoming-instances"],
            });
            queryClient.invalidateQueries({
              queryKey: ["dashbordReport"],
            });
          }}
          incomingInstanceId={rowData?.id as string}
        />
      )}

      {showAssignModal && !isLocked && (
        <AssigneRecord
          record={rowData as unknown as AssignRecordDto}
          isTable={fromTable}
          onClose={() => {
            setShowAssignModal(false);
            if (refetchTable) {
              refetchTable();
            }
            queryClient.invalidateQueries({ queryKey: ["incoming-instances"] });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          onSuccess={() => {
            toast.success(t("msg.successassign"));
            setShowAssignModal(false);
            if (refetchTable) {
              refetchTable();
            }
            queryClient.invalidateQueries({ queryKey: ["incoming-instances"] });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          isOpen={true}
        />
      )}

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

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