import { ColumnDef } from "@tanstack/react-table";
import { renderStatus } from "@/record-management/utils/renderDetails";
import { t } from "i18next";
import { Button } from "@/shared/common/ui/button";
import { NavigateFunction } from "react-router-dom";
import { concat } from "lodash";
import i18n from "i18next";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { useState, useRef, useEffect } from "react";
import { DataTableColumnHeader } from "@/shared/common/ui/dataTableColumnHeader";
import { ProcessedApprovalRecords } from "@/record-management/dto/approval/newApprovalRecordsDto";
import IncomingInstanceDetail from "../../userIncoming/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 MyApprovalColumns = (
  navigate: NavigateFunction,
  localizedName: (name?: { am: string; en: string }) => string,
  pageNo: number,
): ColumnDef<ProcessedApprovalRecords>[] => [
  {
    id: "letterName",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.FileName")}
      />
    ),
    cell: ({ row }) => {
      const record = row.original as ProcessedApprovalRecords;
      // Fix: Access letterName from the nested record object
      const fileName = record.letterName || "N/A";

      return (
        <OverflowTooltip text={fileName} maxWidth={150}>
          <div className="overflow-hidden text-ellipsis whitespace-nowrap">
            {fileName}
          </div>
        </OverflowTooltip>
      );
    },
    enableHiding: true,
    accessorKey: "FileName",
  },
  {
    id: "sendingDepartment",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.SendingDepartment")}
      />
    ),
    cell: ({ row }) => {
      const record = row.original as ProcessedApprovalRecords;
      const initiator = record.initiator;

      if (!initiator) {
        return <div>-</div>;
      }

      const positionName = localizedName(initiator.position?.name);

      return (
        <OverflowTooltip text={positionName} maxWidth={200}>
          <div className="overflow-hidden text-ellipsis whitespace-nowrap">
            {positionName}
          </div>
        </OverflowTooltip>
      );
    },
    enableHiding: true,
    accessorKey: "SendingDepartment",
  },
  {
    id: "subject",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.Subject")}
      />
    ),
    cell: ({ row }) => {
      const record = row.original as ProcessedApprovalRecords;
      const subject = record.content?.[0]?.subject;

      return (
        <OverflowTooltip text={subject} maxWidth={200}>
          <div className="overflow-hidden text-ellipsis whitespace-nowrap">
            {subject}
          </div>
        </OverflowTooltip>
      );
    },
    enableHiding: true,
    accessorKey: "Subject",
  },
  {
    id: "Receiver",
    accessorKey: "Receiver",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.Receiver")}
      />
    ),
    cell: ({ row }) => {
      const record = row.original as ProcessedApprovalRecords;
      const isExternal = record?.recordTypeKey === "external";
      if (isExternal) {
        const units0 = record?.receivingUnits.map(
          (unitItem: any) =>
            localizedName(unitItem.unit?.name) || unitItem.unit?.key || "N/A",
        );
        const units1 =
          record.content?.[0]?.nonSmartReceivers?.map(
            (unitItem: any) => unitItem || "N/A",
          ) || [];
        const unitNames = concat(units0, units1);
        return (
          <div className="space-y-1">
            {unitNames?.length ? (
              unitNames.map((name, idx) => <div key={idx}>{name}</div>)
            ) : (
              <div>No Department</div>
            )}
          </div>
        );
      } else {
        const employeeNames = record.content?.[0]?.receiverEmployees
          ?.map((emp) => localizedName(emp?.employeePosition.employee.name))
          .filter(Boolean);

        const positionNames = record.content?.[0]?.receiverPositions
          ?.map((pos) => localizedName(pos?.position.name))
          .filter(Boolean);
        const receivers = [...employeeNames, ...positionNames];
        return (
          <div className="space-y-1">
            {receivers?.length ? (
              receivers.map((name, idx) => <div key={idx}>{name}</div>)
            ) : (
              <div>No Position</div>
            )}
          </div>
        );
      }
    },
    enableHiding: true,
  },
  {
    accessorKey: "submittedDate",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("ApprovalPage.Date")} />
    ),
    cell: ({ row }) => {
      const original = row.original;

      const isAmharic = i18n.language === "am";
      // Use amharicCreatedAt from the root level of the response for Amharic localization
      const amharicDate =
        original.amharicCreatedAt || original?.amharicSubmittedDate;
      const submittedDate = original?.submittedDate ?? original.createdAt;

      if (isAmharic && amharicDate) {
        return <div>{amharicDate}</div>;
      }

      const formattedDate = submittedDate
        ? new Date(submittedDate).toLocaleDateString("en-US", {
            month: "short", // "Aug"
            day: "numeric", // "7"
            year: "numeric", // "2025"
            hour: "numeric", // "2 PM"
            minute: "numeric", // "30"
          })
        : "-";

      return <div>{formattedDate}</div>;
    },
  },
  {
    accessorKey: "recordStatus",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.RecordStatus")}
      />
    ),
    cell: ({ row }) => {
      return (
        <div>
          {renderStatus(
            row.original?.statusKey ?? "Pending",
            row.original?.statusKey ?? "Pending",
          )}
        </div>
      );
    },
    enableHiding: true,
  },
  {
    accessorKey: "TaskStatus",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("ApprovalPage.Status")} />
    ),
    cell: ({ row }) => {
      const taskStatus =
        row.original?.outgoingHistories?.[0]?.action ?? "Pending";
      return <div>{renderStatus(taskStatus, taskStatus)}</div>;
    },
    enableHiding: true,
  },
  {
    id: "Actions",
    header: () => t("ApprovalPage.Actions"),
    accessorKey: "Actions",
    cell: ({ row }) => {
      const rowData = row.original;

      const handleViewDetails = () => {
        navigate(
          `/record-management/viewProcessedApproval/${rowData?.id}/?page=${pageNo}`,
          {
            // The approval-task shape (with task id, status, nested .record) isn't
            // recoverable from a record id alone, so hand it to the detail page so
            // action buttons there can act on the correct workflow instance.
            state: { approvalRow: rowData },
          },
        );
      };
      return (
        <div className="flex items-center justify-center gap-2">
          <Button
            variant={"viewDetail"}
            onClick={handleViewDetails}
            className="min-w-[110px] text-sm sm:text-base"
          >
            {t("ApprovalPage.View Detail")}
          </Button>
          {rowData?.statusKey === "Dispatched" && (
            <IncomingInstanceDetail
              instanceId={rowData?.id as string}
              instanceType={"outgoing"}
              rowData={rowData}
              fromTable={true}
            />
          )}
        </div>
      );
    },
    enableHiding: true,
  },
];

export default MyApprovalColumns;
