"use client";

import React from "react";
import Link from "next/link";
import { getDefaultProfileImage } from "@/lib/helpers";
import {
  dummyimg,
  dummyimg2,
  dummyimg4,
  img2,
  type LeaderboardTableProps,
  type TableItem,
} from "./achievementsTypes";
import RemoteImage from "@/components/ui/RemoteImage";
import { leaderboardRank, leaderboardValue, hourUnitForDisplay } from "../leaderboardValue";

const LeaderboardTable: React.FC<LeaderboardTableProps> = ({
  data,
  type,
  startRank = 4,
  t,
}) => {
  if (!data || data.length <= 3) {
    return null;
  }

  const tableData = data.slice(3);

  const getDisplayValue = (item: TableItem) => {
    switch (type) {
      case "individuals":
        return `${leaderboardValue(item, type)} ${hourUnitForDisplay(leaderboardValue(item, type), t)}`;
      case "teams":
        return `${leaderboardValue(item, type)} ${t("COMMON.OPPORTUNITY")}`;
      case "companies":
        return `${leaderboardValue(item, type)} ${t("COMMON.SPONSORED_OPPORTUNITIES")}`;
      default:
        return "0";
    }
  };

  const getName = (item: {
    nickname?: string;
    name?: string;
    organization_name?: string;
  }) => {
    return (
      item.nickname ||
      item.name ||
      item.organization_name ||
      t("COMMON.NO_DATA")
    );
  };

  /* The row's real shape: `profile_pic` is nullable and the choice's
     `value_en` is `string | null | undefined` — `websiteChoicePayload()` drops
     a null key, and `getDefaultProfileImage` already treats anything it does
     not recognise as the organization default. */
  const getProfileImage = (item: {
    profile_pic?: string | null;
    gender_display?: { value_en?: string | null } | null;
  }) => {
    if (type === "individuals" && !item.profile_pic) {
      return getDefaultProfileImage(
        item.gender_display?.value_en,
        dummyimg4,
        dummyimg,
        dummyimg2
      );
    } else if ((type === "teams" || type === "companies") && !item.profile_pic) {
      return dummyimg2;
    }
    return item.profile_pic || img2;
  };

  /**
   * One row body, shared by the linked and the unlinked variant so the two can
   * never drift apart the way the duplicated markup used to.
   */
  const renderRow = (item: TableItem, rank: number) => (
    <>
      <div className="flex items-center gap-2 md:gap-3 min-w-0">
        <span className="w-7 md:w-9 shrink-0 text-center text-sm md:text-base font-bold text-[#A8A4C0] tabular-nums">
          {rank}
        </span>
        <RemoteImage
  src={getProfileImage(item)}
  alt={getName(item)}
  width={40}
  height={40}
  className={"w-8 h-8 md:w-10 md:h-10 shrink-0 rounded-full object-cover bg-white ring-1 ring-[#E7E5FF]"}
/>
        <span className="min-w-0 truncate text-xs md:text-sm font-semibold text-[#4A4665]">
          {getName(item)}
        </span>
      </div>
      <div className="shrink-0 rounded-full bg-[#E7E5FF] px-3 py-1.5">
        <span className="text-xs md:text-sm font-bold text-[#5A5380] whitespace-nowrap">
          {getDisplayValue(item)}
        </span>
      </div>
    </>
  );

  return (
    <ul className="flex flex-col gap-2 md:gap-3">
      {tableData.map((item: TableItem, index) => {
        // The backend's rank, so tied rows share a number.
        const rank = leaderboardRank(item, startRank + index);
        const isLinked = getName(item) !== t("COMMON.NO_DATA");
        const rowClass =
          "flex items-center justify-between gap-3 rounded-xl border border-[#E4E2F0] bg-white px-3 md:px-5 py-2 md:py-3 min-h-[56px] md:min-h-[64px]";

        return (
          <li key={item.user_id || item.organization_id || index}>
            {isLinked ? (
              <Link
                href={`/public-profile/${item?.user_id || item?.organization_id}`}
                className={`${rowClass} transition-all duration-200 hover:border-[#C9C4E6] hover:shadow-[0_10px_28px_-18px_rgba(41,36,109,0.45)]`}
              >
                {renderRow(item, rank)}
              </Link>
            ) : (
              <div className={rowClass}>{renderRow(item, rank)}</div>
            )}
          </li>
        );
      })}
    </ul>
  );
};

export default LeaderboardTable;
