import { renderStatus } from "@/record-management/utils/renderDetails";
import { ColumnDef } from "@tanstack/react-table";
import UserRecordsActions from "./userRecordsActions";
import { DataTableColumnHeader } from "@/shared/common/ui/dataTableColumnHeader";
import { t } from "i18next";
import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";
import i18n from "i18next";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";

interface RecordTags {
  isReply?: boolean;
  isSecured?: boolean;
  isUrgent?: boolean;
}

interface UserRecordsColumnOptions {
  onApproveClick?: (row: RecordDto) => void;
}

// Utility component to show tooltip on hover
const OverflowTooltip = ({
  children,
  text,
  maxWidth = 200,
}: {
  children: React.ReactNode;
  text: string;
  maxWidth?: number;
}) => {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <div
          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>
  );
};

interface Badge {
  text: string;
  color: "red" | "yellow" | "green";
}

type NonSmartReceiverLike = {
  name?: string;
  value?: string;
  isCc?: boolean;
  isCC?: boolean;
};

const normalizeNonSmartName = (item: NonSmartReceiverLike | string) => {
  if (typeof item === "string") return item;
  return item?.name || item?.value || "";
};

const getNonSmartOfficeReceivers = (rowData: RecordDto): string[] => {
  const contents = rowData.content || [];

  const directNonSmartOffice = contents.flatMap((contentItem) => {
    const list = contentItem?.nonSmartOfficeReceivers || [];
    return list
      .map((item) =>
        normalizeNonSmartName(item as NonSmartReceiverLike | string),
      )
      .filter(Boolean);
  });

  const legacyNonSmartTo = contents.flatMap((contentItem) => {
    const legacy =
      (contentItem?.nonSmartReceivers as NonSmartReceiverLike[] | undefined) ||
      [];
    return legacy
      .filter((item) => !Boolean(item?.isCc ?? item?.isCC))
      .map((item) => normalizeNonSmartName(item))
      .filter(Boolean);
  });

  const receivingUnitsNonSmart = (rowData.receivingUnits || [])
    .map((unit) => unit?.nonSmartOfficeReceivers || "")
    .filter(Boolean);

  return Array.from(
    new Set([
      ...directNonSmartOffice,
      ...legacyNonSmartTo,
      ...receivingUnitsNonSmart,
    ]),
  );
};

const getSpecialBadges = (tags: RecordTags): Badge[] => {
  const badges: Badge[] = [];

  if (tags.isSecured) {
    badges.push({ text: t("userIncoming.isSecured"), color: "red" });
  }

  if (tags.isUrgent) {
    badges.push({ text: t("userIncoming.isUrgent"), color: "yellow" });
  }

  if (tags.isReply) {
    badges.push({ text: t("userIncoming.replyRecord"), color: "green" });
  }

  return badges;
};

export const UserRecordsColumns = (
  refetch: () => void,
  localizedName: (name?: { am?: string; en?: string }) => string,
  isSecretary: boolean,
  isSelf: boolean,
  waitForAllCollaboratorsBeforeAction: boolean,
  pageNo: number,
  options?: UserRecordsColumnOptions,
  openDropdownId?: string | null,
  onDropdownChange?: (id: string | null) => void,
): ColumnDef<RecordDto>[] => {
  return [
    {
      id: "letterName",
      header: () => t("viewDetail.fileName"),
      accessorKey: "letterName",
      cell: ({ row }) => {
        const rowData = row.original;
        const letterName = rowData.letterName || "_";
        return (
          <div className="flex gap-1">
            <span>{letterName}</span>
          </div>
        );
      },

      enableHiding: true,
    },
    {
      id: "referenceNumber",
      header: () => t("viewDetail.referenceNumber"),
      accessorKey: "referenceNumber",
      cell: ({ row }) => {
        const rowData = row.original;
        const referenceNo =
          rowData.referenceNumber || t("msg.noReferenceNumber");

        return (
          <OverflowTooltip text={referenceNo} maxWidth={150}>
            {referenceNo}
          </OverflowTooltip>
        );
      },
      enableHiding: true,
    },
    {
      id: "Subject",
      header: () => t("userRecord.Subject"),
      cell: ({ row }) => {
        const rowData = row.original;
        const subject = rowData.content?.[0]?.subject || "-";

        return (
          <OverflowTooltip text={subject} maxWidth={200}>
            <div className="overflow-hidden text-ellipsis whitespace-nowrap">
              {subject}
            </div>
          </OverflowTooltip>
        );
      },
      enableHiding: true,
    },
    {
      id: "receiverInfo",
      header: () => t("userRecord.Receiver Info"),
      cell: ({ row }) => {
        const rowData = row.original;
        const recordTypeKey = rowData.recordTypeKey;
        const isInternal =
          recordTypeKey === "internal" ||
          recordTypeKey === "internal_memo" ||
          recordTypeKey === "direct";
        const isExternal = recordTypeKey === "external";

        // INTERNAL: receiver positions
        const receiverPositions =
          rowData.content?.flatMap(
            (item) =>
              item.receiverPositions?.map((rp) =>
                localizedName(rp.position?.name),
              ) || [],
          ) || [];
        // INTERNAL: receiver employees
        const receiverEmployees =
          rowData.content?.flatMap(
            (item) =>
              item.receiverEmployees?.map((re) => {
                return localizedName(re.employeePosition?.employee?.name);
              }) || [],
          ) || [];
        const internalReceivers = [
          ...receiverPositions,
          ...receiverEmployees,
        ].filter(Boolean);

        // EXTERNAL: receiving units
        const receivingUnits =
          rowData.receivingUnits?.map((unitItem) =>
            localizedName(unitItem.unit?.name),
          ) || [];

        // NON-SMART OFFICES (supports both current and legacy payloads)
        const nonSmartOffices = getNonSmartOfficeReceivers(rowData);

        // EXTERNAL: combine receiving units + non-smart
        const externalReceivers = [...receivingUnits].filter(Boolean);

        // FINAL: receivers to show
        const receiversToShow = [
          ...(isInternal ? internalReceivers : []),
          ...(isExternal ? externalReceivers : []),
          ...nonSmartOffices, // always included
        ].filter(Boolean);

        return receiversToShow.length > 0 ? (
          <div className="space-y-1">
            {receiversToShow.map((receiver, i) => (
              <div key={i}>{receiver}</div>
            ))}
          </div>
        ) : (
          <div className="text-gray-500">{t("userRecord.No receivers")}</div>
        );
      },
      enableHiding: true,
    },
    {
      id: "Date",
      header: () => t("userRecord.Date"),
      cell: ({ row }) => {
        const record = row.original;

        // Check current language
        const isAmharic = i18n.language === "am";

        // Use the Amharic date if language is Amharic and date is available
        if (isAmharic && record.amharicCreatedAt) {
          return <div>{record.amharicCreatedAt}</div>;
        }

        // Otherwise, use the default formatted English date
        const safeLocale = ["am", "en"].includes(i18n.language)
          ? i18n.language
          : "en"; // fallback to English if invalid

        const createdDate = record.createdAt
          ? new Date(record.updatedAt).toLocaleDateString(safeLocale, {
              year: "numeric",
              month: "short",
              day: "numeric",
              hour: "numeric",
              minute: "numeric",
            })
          : "-";

        return <div>{createdDate}</div>;
      },
    },

    {
      id: "Status",
      header: () => t("userRecord.Status"),
      cell: ({ row }) => {
        const status = row.original.statusKey;
        const isReply = row.original.inReplyToIncomingInstanceId;
        const isSecured = row.original.isSecured;
        const isUrgent = row.original.isUrgent;
        const isOnReview = row.original.outgoingInstances?.some(
          (i) => i.onReview === true,
        );
        const badges = getSpecialBadges({
          isReply,
          isSecured,
          isUrgent,
        });

        return (
          <div className="flex flex-col gap-2">
            <span>
              {renderStatus(status, isOnReview ? "onReview" : status)}
            </span>

            {badges.length > 0 && (
              <div className="flex flex-wrap gap-1.5">
                {badges.map((badge) => (
                  <span
                    key={`${badge.color}-${badge.text}`}
                    className={`
        inline-flex items-center
        px-2 py-0.5
        text-[10px] font-medium
        rounded-md border
        whitespace-nowrap
        ${
          badge.color === "red"
            ? "text-red-700 bg-red-50 border-red-200"
            : badge.color === "yellow"
              ? "text-yellow-700 bg-yellow-50 border-yellow-200"
              : "text-green-700 bg-green-50 border-green-200"
        }
      `}
                  >
                    {badge.text}
                  </span>
                ))}
              </div>
            )}
          </div>
        );
      },
      enableHiding: true,
    },
    {
      id: "Actions",
      header: () => t("userRecord.Actions"),
      cell: ({ row }) => {
        const rowData = row.original;
        const dropdownId = rowData.id || "";
        return (
          <UserRecordsActions
            rowData={rowData as unknown as RecordDto}
            refetchTable={refetch}
            isSecretary={isSecretary}
            isSelf={isSelf}
            pageIndex={pageNo}
            fromTable={true}
            waitForAllCollaboratorsBeforeAction={
              waitForAllCollaboratorsBeforeAction
            }
            onApproveClick={options?.onApproveClick}
            isDropdownOpen={openDropdownId === dropdownId}
            onDropdownOpenChange={(open) => {
              onDropdownChange?.(open ? dropdownId : null);
            }}
            dropdownId={dropdownId}
          />
        );
      },
    },
  ];
};
