import { ColumnDef } from "@tanstack/react-table";
import { DataTableColumnHeader } from "@/shared/common/ui/dataTableColumnHeader";
import { renderStatus } from "@/record-management/utils/renderDetails";
import { AssignedRecordDto } from "@/record-management/dto/IncomingRecords/taskDto";
import { InternalIncomingRecordActions } from "./internalIncomingRecordsActions";
import { t } from "i18next";
import i18n from "i18next";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { useState, useRef, useEffect } from "react";
import { BellRing } from "lucide-react";

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

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

        return (
          <OverflowTooltip text={letterName} maxWidth={150}>
            {letterName}
          </OverflowTooltip>
        );
      },
      accessorKey: "letterName",
      enableHiding: true,
      size: 150,
    },
    {
      id: "referenceNumber",
      header: () => t("viewDetail.referenceNumber"),
      accessorKey: "referenceNumber",
      cell: ({ row }) => {
        const referenceNo = row?.original?.record?.referenceNumber || "";
        const recordTypeKey = row?.original?.record?.recordTypeKey || "";
        return (
          <OverflowTooltip text={referenceNo} maxWidth={150}>
            {referenceNo === "" ? (
              <span className="inline-block px-3 py-1 text-xs font-medium text-blue-700 bg-blue-100 rounded-full border border-blue-200">
                {recordTypeKey === "direct"
                  ? t("nav.direct")
                  : t("nav.internal_memo")}
              </span>
            ) : (
              referenceNo
            )}
          </OverflowTooltip>
        );
      },
      enableHiding: true,
      size: 150,
    },
    {
      id: "Sending_Department",
      header: () => t("userIncoming.Sending Department"),
      accessorKey: "Sending_Department",
      cell: ({ row }) => {
        const positionName = row.original.record.initiator?.position?.name;
        const localized = localizedName(positionName); // ✅ dynamic translation
        const displayText = localized || t("userIncoming.No Department");

        return (
          <OverflowTooltip text={displayText} maxWidth={200}>
            {displayText}
          </OverflowTooltip>
        );
      },
      enableHiding: true,
      size: 200,
    },
    {
      id: "subject",
      header: () => t("userIncoming.Subject"),
      cell: ({ row }) => {
        const subject = row.original.record.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.record.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: "dispatchedDate",
      header: () => t("userIncoming.Date"),
      cell: ({ row }) => {
        const record = row.original;

        const isAmharic = i18n.language === "am";
        const amharicDate =
          record?.record?.amharicDispatchedDate || record?.amharicCreatedAt;
        const createdAt = record.record?.dispatchedDate || record?.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: "Task Status",
	      header: () => t("userIncoming.Status"),
      cell: ({ row }) => {
        const rowData = row.original;
        const statusElement = rowData.status
          ? renderStatus(rowData.status, rowData.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 (
          <InternalIncomingRecordActions
            rowData={rowData}
            refetchTable={refetch}
            isSecretary={isSecretary}
            isSelf={isSelf}
            pageIndex={pageNo}
            fromTable={true}
            isDropdownOpen={openDropdownId === dropdownId}
            onDropdownOpenChange={(open) => {
              onDropdownChange?.(open ? dropdownId : null);
            }}
            dropdownId={dropdownId}
          />
        );
      },
      enableHiding: true,
      accessorKey: "Actions",
    },
  ];
};
