import { ColumnDef } from "@tanstack/react-table";
import { DataTableColumnHeader } from "@/shared/common/ui/dataTableColumnHeader";

import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import AssignCCRecord from "./AssignCCRecord";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { MoreHorizontal, Forward } from "lucide-react";
import { MemoDto } from "@/record-management/components/hooks/useCCIncomingRecords";
import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import { useNavigate } from "react-router-dom";
import { t } from "i18next";
import i18n from "i18next";
import { hasSeen } from "@/record-management/services/api/incomingRecordService";
import { useCallback, useRef, useEffect } from "react";
import { renderStatus } from "@/record-management/utils/renderDetails";

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

// CC Incoming Actions component
export function CCIncomingRecordActions({
  rowData,
  refetch,
  isSecretary,
  isSelf,
  pageIndex,
  isTable,
  isForYourReference = false,
  canAssignCC = true,
  calledFrom,
  isDropdownOpen = false,
  onDropdownOpenChange,
  dropdownId = "",
}: {
  rowData: MemoDto;
  refetch?: () => void;
  isSecretary?: boolean;
  isSelf: boolean;
  pageIndex?: number;
  isTable: boolean;
  isForYourReference?: boolean;
  canAssignCC?: boolean;
  calledFrom?: string;
  isDropdownOpen?: boolean;
  onDropdownOpenChange?: (open: boolean) => void;
  dropdownId?: string;
}) {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [isAssignDialogOpen, setIsAssignDialogOpen] = useState(false);
  const secretaryView = isSelf ? "" : "parent";
  const isAssignable = !rowData?.isDelegation;
  const isLocked = rowData?.isLocked;
  const handleViewDetails = () => {
    const detailPath =
      calledFrom === "ForYourReference" ? "for-your-reference" : "cc";
    const baseUrl = `/record-management/viewIncoming/${detailPath}/${rowData?.id}/?page=${pageIndex}`;
    const url = secretaryView === "parent" ? `${baseUrl}&view=parent` : baseUrl;

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

  const handleSeen = useCallback(async () => {
    if (!rowData?.id) throw new Error("Invalid Record ID");
    await hasSeen(rowData?.id, isForYourReference);
    if (refetch) await refetch();
    queryClient.invalidateQueries({ queryKey: ["incoming-cc"] });
    queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
    // Refetch useReportByHooks by invalidating its underlying query keys
    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, refetch, rowData?.id]);

  const openAssignDialog = () => {
    setIsAssignDialogOpen(true);
  };

  const closeAssignDialog = () => {
    setIsAssignDialogOpen(false);
    navigate("/record-management/userIncoming/cc");
  };
  return (
    <>
      {isTable ? (
        <div className="flex items-center gap-1">
          <Button
            variant="viewDetail"
            className="min-w-[110px]"
            onClick={() => handleViewDetails()}
          >
            {t("userIncoming.View Detail")}
          </Button>
          {calledFrom !== "ForYourReference" && canAssignCC && !isLocked && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 p-0">
                  <span className="sr-only">Open menu</span>
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                {isAssignable && (
                  <DropdownMenuItem onSelect={openAssignDialog}>
                    <Forward className="mr-2 h-4 w-4" />
                    {t("userIncoming.Assign CC")}
                  </DropdownMenuItem>
                )}
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
      ) : (
        canAssignCC &&
        !isLocked &&
        isAssignable && (
          <Button
            variant={getActionButtonVariant("Assign")}
            onClick={openAssignDialog}
          >
            <Forward className="h-4 w-4" />
            <span>{t("userIncoming.Assign")}</span>
          </Button>
        )
      )}

      <AssignCCRecord
        open={isAssignDialogOpen}
        onClose={closeAssignDialog}
        record={rowData}
        refetch={refetch ? refetch : () => {}}
      />
    </>
  );
}

export const CCIncomingRecordsColumns = (
  refetch: () => void,
  localizedName: (name?: { am?: string; en?: string }) => string,
  isSecretary: boolean,
  isSelf: boolean,
  pageNo: number,
  isForYourReference: boolean = false,
  canAssignCC: boolean = true,
  calledFrom: string,
  openDropdownId?: string | null,
  onDropdownChange?: (id: string | null) => void,
): ColumnDef<MemoDto>[] => [
  {
    id: "referenceNumber",
    header: () => t("viewDetail.referenceNumber"),
    accessorKey: "referenceNumber",
    cell: ({ row }) => {
      const referenceNo = row?.original?.referenceNumber || "";
      const recordTypeKey = row?.original?.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: "sendingDepartment",
    header: () => t("userIncoming.Sending Department"),
    cell: ({ row }) => {
      const rowData = row.original;
      const initiatorPosition = (rowData as any)?.initiatorPosition;
      const positionName =
        (typeof initiatorPosition === "string"
          ? initiatorPosition
          : localizedName(initiatorPosition?.name || initiatorPosition)) ||
        rowData.initiator?.position
          ? localizedName(rowData.initiator?.position?.name)
          : localizedName(rowData.initiator?.employee?.name);
      const displayText = positionName || t("userIncoming.No Department");

      return (
        <OverflowTooltip text={displayText} maxWidth={200}>
          {displayText}
        </OverflowTooltip>
      );
    },
    enableHiding: true,
    accessorKey: "sendingDepartment",
    size: 200,
  },
  // {
  //   id: "recordTypeKey",
  //   header: ({ column }) => (
  //     <DataTableColumnHeader
  //       column={column}
  //       title={t("userIncoming.Record Type")}
  //     />
  //   ),
  //   cell: ({ row }) => {
  //     const recordType = row?.original?.recordTypeKey;
  //     return recordType
  //       ? recordType
  //       : t("userIncoming.No Record Type");
  //   },
  //   accessorKey: "referenceNumber",
  //   enableHiding: true,
  // },
  {
    id: "Subject",
    header: () => t("userIncoming.Subject"),
    accessorKey: "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>
      );
    },
    enableHiding: true,
    size: 200,
  },
  {
    accessorKey: "createdAt",
    header: () => t("userIncoming.Date"),
    cell: ({ row }) => {
      const record = row.original;

      const isAmharic = i18n.language === "am";
      const amharicDate =
        record.amharicDispatchedDate ?? record.amharicCreatedAt;
      const createdAt = 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 status =
        row.original.content?.[0]?.ccs?.[0]?.status || rowData.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 (
        <CCIncomingRecordActions
          rowData={rowData}
          refetch={refetch}
          isSecretary={isSecretary}
          isSelf={isSelf}
          pageIndex={pageNo}
          calledFrom={calledFrom}
          isTable={true}
          isForYourReference={isForYourReference}
          canAssignCC={canAssignCC}
          isDropdownOpen={openDropdownId === dropdownId}
          onDropdownOpenChange={(open) => {
            onDropdownChange?.(open ? dropdownId : null);
          }}
          dropdownId={dropdownId}
        />
      );
    },
    enableHiding: true,
    accessorKey: "Actions",
  },
];
