"use client";

import { Search } from "lucide-react";
import { useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";

import { DeveloperLeaderboard } from "@/components/analytics/DeveloperLeaderboard";
import { KpiCard } from "@/components/analytics/KpiCard";
import { PrinzipVelocityChart } from "@/components/analytics/PrinzipVelocityChart";
import { Section } from "@/components/analytics/Section";
import { VelocityScatter } from "@/components/analytics/VelocityScatter";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { useDeveloperDetail, useTopDevelopers } from "@/lib/analytics-api";

function DevelopersInner() {
  const search = useSearchParams();
  const focusedId = search.get("id") ?? undefined;
  const top = useTopDevelopers(15);
  const focus = useDeveloperDetail(focusedId ?? "");

  // Debounced 300ms search over the leaderboard (client-side filter — the
  // top-15 list is already in memory, no extra request).
  const [searchInput, setSearchInput] = useState("");
  const debouncedSearch = useDebouncedValue(searchInput, 300);

  const focused = focusedId ? focus.data : null;
  const topNames: Record<string, string> = Object.fromEntries(
    (top.data ?? []).map((r) => [r.developer_id, r.developer_name]),
  );

  // Top-3 by jk_count (complexes count) from the leaderboard, falling back to
  // static defaults if data is not yet available.
  const top3Ids = (top.data ?? [])
    .slice()
    .sort((a, b) => (b.jk_count ?? 0) - (a.jk_count ?? 0))
    .slice(0, 3)
    .map((r) => r.developer_id);

  const defaultTop3 =
    top3Ids.length >= 3 ? top3Ids : ["6208_0", "5791_0", "5832_0"];

  const compareIds = focusedId
    ? [focusedId, ...defaultTop3.filter((x) => x !== focusedId).slice(0, 2)]
    : defaultTop3;

  return (
    <>
      {focused ? (
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
          <KpiCard
            label="Девелопер"
            value={focused.developer_name}
            hint={`id ${focused.developer_id}`}
          />
          <KpiCard
            label="Объём Свердл"
            value={focused.sverdl_sqm_th?.toFixed(0) ?? "—"}
            unit="тыс м²"
          />
          <KpiCard
            label="Sold %"
            value={focused.sverdl_sold_pct?.toFixed(0) ?? "—"}
            unit="%"
          />
          <KpiCard
            label="Средний метраж"
            value={focused.avg_area_sqm?.toFixed(1) ?? "—"}
            unit="м²"
            hint={`1-к ${focused.pct_one ?? 0}% · 3-к+ ${focused.pct_three_plus ?? 0}%`}
          />
        </div>
      ) : null}

      <Section
        title="Топ-15 девелоперов Свердл"
        subtitle="Сортировка по объёму строительства (тыс м²). Δ пп — рост sold% за всю историю DOM.РФ realization. Клик по строке — drill-down."
        right={
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              border: "1px solid var(--border-strong)",
              borderRadius: 8,
              padding: "6px 10px",
              background: "var(--bg-card)",
            }}
          >
            <Search
              size={16}
              strokeWidth={1.5}
              color="var(--fg-tertiary)"
              aria-hidden
            />
            <input
              type="search"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              placeholder="Найти девелопера…"
              aria-label="Поиск девелопера по названию"
              style={{
                border: "none",
                outline: "none",
                fontSize: 14,
                width: 200,
                background: "transparent",
                color: "var(--fg-primary)",
              }}
            />
          </div>
        }
      >
        <DeveloperLeaderboard highlight={focusedId} query={debouncedSearch} />
      </Section>

      <Section
        title="Velocity-карта: победители vs затоваривание"
        subtitle="Ось X — объём строительства, Y — Δ sold%. Зелёные — растущий sold%, красные — падающий (риск затоваривания)."
      >
        <VelocityScatter />
      </Section>

      <Section
        title={
          focusedId && focused
            ? `Сравнение sold% — ${focused.developer_name} vs benchmarks`
            : `Сравнение sold% — топ-3 девелопера`
        }
        subtitle="Ежемесячная история DOM.РФ realization (endpoint=developer)."
      >
        <PrinzipVelocityChart
          developerIds={compareIds}
          developerNames={
            focused
              ? { ...topNames, [focused.developer_id]: focused.developer_name }
              : topNames
          }
        />
      </Section>
    </>
  );
}

export default function DevelopersPage() {
  return (
    <Suspense fallback={<div>Загрузка…</div>}>
      <DevelopersInner />
    </Suspense>
  );
}
