"use client";

import Link from "next/link";
import { useMemo, useState } from "react";

import { useTopDevelopers } from "@/lib/analytics-api";
import type { DeveloperTopRow } from "@/types/analytics";

type SortKey =
  | "sverdl_sqm_th"
  | "sold_pct"
  | "sold_delta_pp"
  | "avg_area_sqm"
  | "pct_three_plus";

const COLS: {
  key: SortKey;
  label: string;
  format: (v: number | null) => string;
}[] = [
  {
    key: "sverdl_sqm_th",
    label: "тыс м²",
    format: (v) => (v != null ? v.toFixed(0) : "—"),
  },
  {
    key: "sold_pct",
    label: "sold %",
    format: (v) => (v != null ? `${v.toFixed(0)}` : "—"),
  },
  {
    key: "sold_delta_pp",
    label: "Δ пп",
    format: (v) =>
      v != null ? (v > 0 ? `+${v.toFixed(0)}` : v.toFixed(0)) : "—",
  },
  {
    key: "avg_area_sqm",
    label: "ср. м²",
    format: (v) => (v != null ? v.toFixed(1) : "—"),
  },
  {
    key: "pct_three_plus",
    label: "3-к+ %",
    format: (v) => (v != null ? v.toFixed(0) : "—"),
  },
];

export function DeveloperLeaderboard({
  highlight,
  query,
}: {
  highlight?: string;
  /** Case-insensitive substring filter on developer_name (debounced upstream). */
  query?: string;
}) {
  const { data, isLoading } = useTopDevelopers(15);
  const [sortBy, setSortBy] = useState<SortKey>("sverdl_sqm_th");
  const [desc, setDesc] = useState(true);

  const rows = useMemo(() => {
    const needle = (query ?? "").trim().toLocaleLowerCase("ru");
    const arr = (data ?? []).filter((r) =>
      needle ? r.developer_name.toLocaleLowerCase("ru").includes(needle) : true,
    );
    arr.sort((a, b) => {
      const av = (a[sortBy] ?? -Infinity) as number;
      const bv = (b[sortBy] ?? -Infinity) as number;
      return desc ? bv - av : av - bv;
    });
    return arr;
  }, [data, sortBy, desc, query]);

  const click = (k: SortKey) => {
    if (k === sortBy) setDesc(!desc);
    else {
      setSortBy(k);
      setDesc(true);
    }
  };

  if (isLoading)
    return <div style={{ padding: 16, color: "#5b6066" }}>Загрузка…</div>;

  if (rows.length === 0)
    return (
      <div style={{ padding: 16, color: "#5b6066", fontSize: 14 }}>
        {query?.trim()
          ? `Ничего не найдено по запросу «${query.trim()}».`
          : "Данные пока недоступны."}
      </div>
    );

  return (
    <div style={{ overflowX: "auto" }}>
      <table
        style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}
      >
        <thead>
          <tr style={{ background: "#f6f7f9" }}>
            <th style={th}>#</th>
            <th style={{ ...th, textAlign: "left" }}>Девелопер</th>
            {COLS.map((c) => (
              <th
                key={c.key}
                style={{ ...th, cursor: "pointer", userSelect: "none" }}
                onClick={() => click(c.key)}
              >
                {c.label}
                {sortBy === c.key ? (desc ? " ↓" : " ↑") : ""}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((r: DeveloperTopRow, i) => {
            const isHi = highlight && r.developer_id === highlight;
            return (
              <tr
                key={r.developer_id}
                style={{
                  background: isHi ? "#fef9c3" : i % 2 ? "#fafbfc" : "#fff",
                  borderBottom: "1px solid #eef0f3",
                }}
              >
                <td style={td}>{i + 1}</td>
                <td style={{ ...td, textAlign: "left" }}>
                  <Link
                    href={`/analytics/developers?id=${r.developer_id}`}
                    style={{ color: "#1d4ed8", textDecoration: "none" }}
                  >
                    {r.developer_name}
                  </Link>
                </td>
                {COLS.map((c) => {
                  const value = r[c.key] as number | null;
                  let color = "#111";
                  if (c.key === "sold_delta_pp" && value != null) {
                    color =
                      value > 5
                        ? "#0a7a3a"
                        : value < -5
                          ? "#b3261e"
                          : "#5b6066";
                  }
                  return (
                    <td key={c.key} style={{ ...td, color }}>
                      {c.format(value)}
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

const th = {
  padding: "10px 12px",
  textAlign: "right" as const,
  fontWeight: 600,
  borderBottom: "1px solid #e6e8ec",
  color: "#374151",
};
const td = {
  padding: "10px 12px",
  textAlign: "right" as const,
};
