import { ColumnDef } from "@tanstack/react-table";
import { renderStatus } from "@/record-management/utils/renderDetails";

import {
  Activity,
  BellRing,
  EllipsisVertical,
  FileText,
  Forward,
  Lock,
  MessageSquareMore,
  Repeat2,
  SearchCheck,
  SquareX,
  X,
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { Button } from "@/shared/common/ui/button";
import { useState, useRef, useEffect } from "react";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";

import { useNavigate } from "react-router-dom";

import React from "react";
import { t } from "i18next";
import AcceptIncomingRecord from "../internalIncomingRecords/AcceptIncoming";
import { toast } from "sonner";
import i18n from "@/i18n";
import { DisplayRecordDto } from "../internalIncomingRecords/internalIncomingRecordsActions";
import ParentContainer from "../../recordOfficer/recordDetails/ParentAssignementContainer";
import { useQueryClient } from "@tanstack/react-query";
import RejectIncomingRecord from "../internalIncomingRecords/RejectIncoming";
import { IncomingLetterItem } from "@/record-management/dto/IncomingRecords/incomingTasksDto";
import AssigneRecordV2 from "../internalIncomingRecords/AssignRecordV2";
import useCanAssignRecord from "@/record-management/components/hooks/useCanAssignRecord";
import RemarkCreationDialog from "../remarkCreationCard";
import { useTranslation } from "react-i18next";
import IncomingInstanceDetail from "../IncomingInstanceDetail";

// Utility component to show tooltip only when text overflows
const OverflowTooltip = ({
  children,
  text,
  maxWidth = 200,
}: {
  children: React.ReactNode;
  text: string;
  maxWidth?: number;
}) => {
  const [isOverflowing, setIsOverflowing] = useState(false);
  const textRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const checkOverflow = () => {
      if (textRef.current) {
        const element = textRef.current;
        setIsOverflowing(element.scrollWidth > element.clientWidth);
      }
    };

    checkOverflow();
    window.addEventListener("resize", checkOverflow);
    return () => window.removeEventListener("resize", checkOverflow);
  }, [text]);

  if (isOverflowing) {
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <div
            ref={textRef}
            className="overflow-hidden text-ellipsis whitespace-nowrap"
            style={{ maxWidth: `${maxWidth}px` }}>
            {children}
          </div>
        </TooltipTrigger>
        <TooltipContent>
          <p className="max-w-xs break-words">{text}</p>
        </TooltipContent>
      </Tooltip>
    );
  }

  return (
    <div
      ref={textRef}
      className="overflow-hidden text-ellipsis whitespace-nowrap"
      style={{ maxWidth: `${maxWidth}px` }}>
      {children}
    </div>
  );
};

const TaskUpdateBadge = ({
  latestRemarkAt,
  className = "",
}: {
  latestRemarkAt?: string | null;
  className?: string;
}) => {
  const isRemark = !!latestRemarkAt;

  return (
    isRemark && (
      <span
        className={`inline-flex items-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"
        } ${className}`}>
        {t("userIncoming.remarkAdded", "Remark Added")}
      </span>
    )
  );
};

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);
};

// External Incoming Actions component
export const ExternalIncomingRecordActionsV2 = React.memo(
  ({
    rowData,
    refetchTable,
    isSelf,
    pageIndex,
    fromTable,
    isDropdownOpen = false,
    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 [showAcceptDialog, setShowAcceptDialog] = useState(false);
    const [showRejectDialog, setShowRejectDialog] = useState(false);
    const [showRemarkDialog, setShowRemarkDialog] = useState(false);
    const [selectedRecord, setSelectedRecord] =
      useState<DisplayRecordDto | null>(null);
    const [isPanelOpen, setIsPanelOpen] = useState(false);
    const queryClient = useQueryClient();
    const secretaryView = isSelf ? "" : "parent";

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

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

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

    const openRemarkDialog = (e: PreventableEvent) => {
      e.preventDefault();
      
      setShowRemarkDialog(true);
    };

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

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

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

    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 { canAssignRecord } = useCanAssignRecord();

    const isAcceptable = !isRejected && isInProgress;
    const isAssignable = !rowData?.isDelegation && canAssignRecord;
    const isRejectable = !rowData?.isDelegation && !isRejected && isInProgress;
    const isRemarkable = isReassigned;
    const isReplyable = !isRejected && isInProgress;

    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 gap-1 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={handleViewDetails}>
                {t("userIncoming.View Detail")}
              </Button>
              <TaskUpdateBadge
                latestRemarkAt={latestRemarkAt}
                className="mt-1"
              />
            </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-8 w-8 p-0 sm:h-8 sm:w-8 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">
                  {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" />
                      {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 */}
            <Button
              className="bg-transparent hover:bg-transparent text-primary hover:text-primary h-12 w-12 sm:h-10 sm:w-10 p-0"
              onClick={(e) => {
                e.preventDefault();
                const record = rowData;
                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("userIncoming.View Detail")}>
              <Activity />
            </Button>
            <IncomingInstanceDetail
              instanceId={rowData?.incomingInstances?.[0]?.id as string}
              rowData={rowData}
            />
            {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-green-50 to-emerald-50/50 dark:from-green-900/20 dark:to-emerald-900/10">
                    <div className="flex items-center gap-3">
                      <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-green-100 dark:bg-green-900/40">
                        <FileText className="h-5 w-5 text-green-600 dark:text-green-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="outline"
                      size="sm"
                      onClick={openAcceptDialog}
                      className="h-9 px-4 flex items-center gap-2 rounded-full bg-gradient-to-r from-emerald-50 to-green-50 border-emerald-200 hover:from-emerald-100 hover:to-green-100 hover:border-emerald-300 hover:text-emerald-700 transition-all duration-300 shadow-sm hover:shadow-md 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="h-4 w-4 text-emerald-600" />
                      <span className="text-sm font-medium text-emerald-700">
                        {t("userIncoming.Accept")}
                      </span>
                    </Button>
                  )}
                  {effectiveIsAssignable && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={openAssignDialog}
                      className="h-9 px-4 flex items-center gap-2 rounded-full bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200 hover:from-blue-100 hover:to-indigo-100 hover:border-blue-300 hover:text-blue-700 transition-all duration-300 shadow-sm hover:shadow-md 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="h-4 w-4 text-blue-600" />
                      <span className="text-sm font-medium text-blue-700">
                        {t("userIncoming.Assign")}
                      </span>
                    </Button>
                  )}
                  {effectiveIsReplyable && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleReply}
                      className="h-9 px-4 flex items-center gap-2 rounded-full bg-gradient-to-r from-amber-50 to-orange-50 border-amber-200 hover:from-amber-100 hover:to-orange-100 hover:border-amber-300 hover:text-amber-700 transition-all duration-300 shadow-sm hover:shadow-md 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="h-4 w-4 text-amber-600" />
                      <span className="text-sm font-medium text-amber-700">
                        {t("userIncoming.reply")}
                      </span>
                    </Button>
                  )}
                  {effectiveIsRejectable && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={openRejectDialog}
                      className="h-9 px-4 flex items-center gap-2 rounded-full bg-gradient-to-r from-rose-50 to-red-50 border-rose-200 hover:from-rose-100 hover:to-red-100 hover:border-rose-300 hover:text-rose-700 transition-all duration-300 shadow-sm hover:shadow-md 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="h-4 w-4 text-rose-600" />
                      <span className="text-sm font-medium text-rose-700">
                        {t("userIncoming.Reject")}
                      </span>
                    </Button>
                  )}

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

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

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

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

export const ExternalIncomingRecordsColumnsV2 = (
  refetch: () => void,
  localizedName: (name?: { am?: string; en?: string }) => string,
  isSecretary: boolean,
  isSelf: boolean,
  pageNo: number,
  openDropdownId?: string | null,
  onDropdownChange?: (id: string | null) => void,
  onAssign?: (rowData: IncomingLetterItem) => void,
): ColumnDef<IncomingLetterItem>[] => [
  {
    id: "letterName",
    header: () => t("viewDetail.fileName1"),
    cell: ({ row }) => {
      const letterName = row?.original?.letterName || "-";

      return (
        <OverflowTooltip text={letterName} maxWidth={150}>
          {letterName}
        </OverflowTooltip>
      );
    },
    accessorKey: "letterName",
    enableHiding: true,
    size: 150,
  },
  {
    id: "referenceNumber",
    header: () => t("viewDetail.referenceNumber"),
    cell: ({ row }) => {
      const referenceNo = row?.original?.referenceNumber || "";

      return (
        <OverflowTooltip text={referenceNo} maxWidth={150}>
          {referenceNo}
        </OverflowTooltip>
      );
    },
    accessorKey: "referenceNumber",
    enableHiding: true,
    size: 150,
  },
  {
    id: "organizationName",
    header: () => t("userIncoming.Sending Organization"),
    cell: ({ row }) => {
      const organizationName =
        row?.original?.metadata?.organizationName ||
        row?.original?.initiator?.unit?.organization?.name;

      const localizedOrgName = localizedName(organizationName);
      const displayText =
        localizedOrgName || t("userIncoming.No Sending organization");

      return (
        <OverflowTooltip text={displayText} maxWidth={200}>
          {displayText}
        </OverflowTooltip>
      );
    },
    accessorKey: "organizationName",
    enableHiding: true,

    size: 200,
  },
  {
    id: "subject",
    header: () => t("userIncoming.Subject"),
    cell: ({ row }) => {
      const subject = row.original.content?.[0].subject;
      const displayText = subject ? subject : t("userIncoming.No Subject");

      return (
        <OverflowTooltip text={displayText} maxWidth={200}>
          {displayText}
        </OverflowTooltip>
      );
    },

    accessorKey: "Subject",
    enableHiding: true,
    size: 200,
  },
  {
    id: "isUrgent",
    header: () => t("userIncoming.Is Urgent"),
    cell: ({ row }) => {
      const rowData = row.original;
      const isUrgent = rowData.isUrgent;

      return (
        <span
          className={`relative inline-flex items-center px-2 py-1 rounded-md text-sm font-semibold ${
            isUrgent
              ? "bg-yellow-100 text-yellow-800"
              : "bg-gray-100 text-gray-600"
          }`}>
          {isUrgent && (
            <span className="absolute -top-0 -right-5 flex h-4 w-4">
              {/* Pulsing ring */}
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>

              {/* Bell icon stays visible */}
              <span className="relative inline-flex items-center justify-center pt-3">
                <BellRing className="h-5 w-5 text-red-500" />
              </span>
            </span>
          )}

          {isUrgent ? t("common.yes") : t("common.no")}
        </span>
      );
    },
    enableHiding: true,
    accessorKey: "isUrgent",
  },
  {
    accessorKey: "createdAt",
    header: () => t("userIncoming.Date"),
    cell: ({ row }) => {
      const record = row.original;
      const lastInstance = record?.incomingInstances?.[0];
      const isAmharic = i18n.language === "am";
      const amharicDate = lastInstance?.amharicCreatedAt;
      const createdAt = lastInstance?.createdAt;

      let displayText = "-";
      if (isAmharic && amharicDate) {
        displayText = amharicDate;
      } else if (createdAt) {
        displayText = new Date(createdAt).toLocaleDateString(i18n.language, {
          year: "numeric",
          month: "short",
          day: "numeric",
          hour: "numeric",
          minute: "numeric",
        });
      }

      return displayText;
    },
    size: 150,
  },
  {
    id: "status",
    header: () => t("userRecord.Status"),
    cell: ({ row }) => {
      const rowData = row.original;
      const lastInstance = rowData?.incomingInstances?.[0];
      const status = lastInstance?.status;
      const statusElement = status ? renderStatus(status, status) : null;

      return statusElement;
    },
    accessorKey: "TaskStatus",
    enableHiding: true,
    size: 120,
  },
  {
    id: "Actions",
    header: t("userIncoming.Actions"),
    cell: ({ row }) => {
      const rowData = row.original;
      const dropdownId = rowData.id || "";
      return (
        <ExternalIncomingRecordActionsV2
          rowData={rowData}
          refetchTable={refetch}
          isSecretary={isSecretary}
          isSelf={isSelf}
          pageIndex={pageNo}
          fromTable={true}
          isDropdownOpen={openDropdownId === dropdownId}
          onDropdownOpenChange={(open) => {
            onDropdownChange?.(open ? dropdownId : null);
          }}
          dropdownId={dropdownId}
          onAssign={onAssign}
        />
      );
    },
    enableHiding: true,
    accessorKey: "Actions",
  },
];
