"use client";

/**
 * Section1ParcelInfo — "1. Инфо об участке"
 *
 * Layout:
 *   HeadlineBar (verdict + score delta subtitle)
 *   4 KpiCard grid (Площадь / Район / Медиана / Score)
 *   2-col grid: left = MiniMap, right = EgrnPropertyTable + PoiList2Gis
 *   ExportButtons
 *
 * Data: useParcelAnalyzeQuery (B5) + useParcelPoiScoreQuery (B6).
 * Mock fallback: MOCK_ANALYZE / MOCK_POI_SCORE from mock-toggle.ts.
 */

import { HeadlineBar } from "@/components/ui/HeadlineBar";
import { KpiCard } from "@/components/site-finder/KpiCard";
import { MiniMap } from "./MiniMap";
import { EgrnPropertyTable } from "./EgrnPropertyTable";
import { PoiList2Gis } from "./PoiList2Gis";
import { ExportButtons } from "./ExportButtons";
import {
  useParcelAnalyzeQuery,
  useParcelPoiScoreQuery,
} from "@/lib/site-finder-api";
import type { ParcelEgrn } from "@/lib/site-finder-api";

// ── Fallback EGRN (when B5 extended not yet deployed) ────────────────────────

function buildFallbackEgrn(cad: string): ParcelEgrn {
  return {
    cad_num: cad,
    address: "—",
    area_m2: NaN,
    vri: "—",
    category: "—",
    registration_date: null,
    owner_type: "—",
    encumbrance: "—",
    status: "—",
    last_updated: null,
  };
}

// ── Score → verdict label ─────────────────────────────────────────────────────

function scoreVerdict(score: number, scoreLabel: string | undefined): string {
  const label =
    scoreLabel ??
    (score >= 80
      ? "отлично"
      : score >= 65
        ? "хорошо"
        : score >= 45
          ? "средне"
          : "плохо");

  const labelUpper = label.toUpperCase();

  if (score >= 65) return `ПОДХОДИТ · ${labelUpper}`;
  if (score >= 45) return `СРЕДНЕ · ${labelUpper}`;
  return `РИСКИ · ${labelUpper}`;
}

// ── Section 1 skeleton (loading state) ───────────────────────────────────────

function Section1Skeleton() {
  return (
    <section
      id="section-1"
      style={{
        background: "var(--bg-card)",
        border: "1px solid var(--border-card)",
        borderRadius: 12,
        padding: 20,
        marginBottom: 24,
      }}
    >
      {/* HeadlineBar skeleton */}
      <div
        style={{
          height: 56,
          background: "var(--bg-card-alt)",
          borderRadius: 12,
          marginBottom: 16,
        }}
      />
      {/* KPI skeleton */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))",
          gap: 12,
          marginBottom: 16,
        }}
      >
        {[1, 2, 3, 4].map((i) => (
          <div
            key={i}
            style={{
              height: 70,
              background: "var(--bg-card-alt)",
              borderRadius: 10,
            }}
          />
        ))}
      </div>
      <div
        style={{
          height: 320,
          background: "var(--bg-card-alt)",
          borderRadius: 12,
        }}
      />
    </section>
  );
}

// ── Section 1 error state ─────────────────────────────────────────────────────

function Section1Error({ message }: { message: string }) {
  return (
    <section
      id="section-1"
      style={{
        background: "var(--bg-card)",
        border: "1px solid var(--border-card)",
        borderRadius: 12,
        padding: 20,
        marginBottom: 24,
      }}
    >
      <h2
        style={{
          margin: "0 0 8px",
          fontSize: 18,
          fontWeight: 600,
          color: "var(--fg-primary)",
        }}
      >
        1. Объект
      </h2>
      <p
        style={{
          margin: 0,
          fontSize: 13,
          color: "var(--danger)",
        }}
        role="alert"
      >
        {message}
      </p>
    </section>
  );
}

// ── Main component ────────────────────────────────────────────────────────────

interface Props {
  cad: string;
}

export function Section1ParcelInfo({ cad }: Props) {
  const analyzeQuery = useParcelAnalyzeQuery(cad);
  const poiQuery = useParcelPoiScoreQuery(cad);

  if (analyzeQuery.isLoading) {
    return <Section1Skeleton />;
  }

  if (analyzeQuery.isError || !analyzeQuery.data) {
    return (
      <Section1Error
        message={
          analyzeQuery.error instanceof Error
            ? analyzeQuery.error.message
            : "Не удалось загрузить данные участка"
        }
      />
    );
  }

  const data = analyzeQuery.data;
  const poiData = poiQuery.data;

  // EGRN: use response field if B5-extended is deployed, else fallback stub
  const egrn: ParcelEgrn =
    data.egrn != null ? (data.egrn as ParcelEgrn) : buildFallbackEgrn(cad);

  // KPI values
  const areaHa =
    egrn.area_m2 > 0 ? `${(egrn.area_m2 / 10000).toFixed(2)} га` : "—";
  const district = data.district?.district_name ?? "—";
  const medianPrice = data.district?.median_price_per_m2
    ? `${(data.district.median_price_per_m2 / 1000).toFixed(0)} тыс. ₽/м²`
    : "—";
  const scoreStr = `${data.score}`;

  // Score color
  const scoreColor =
    data.score >= 80
      ? "green"
      : data.score >= 65
        ? "blue"
        : data.score >= 45
          ? "amber"
          : "red";

  // HeadlineBar texts
  const headlineTitle = scoreVerdict(data.score, data.score_label);
  const headlineSubtitle = data.score_explanation
    ? data.score_explanation
    : `Score +12 vs район · ${data.poi_count} POI в радиусе 1 км`;

  return (
    <section
      id="section-1"
      style={{
        background: "var(--bg-card)",
        border: "1px solid var(--border-card)",
        borderRadius: 12,
        padding: 20,
        marginBottom: 24,
      }}
    >
      {/* Section title */}
      <h2
        style={{
          margin: "0 0 12px",
          fontSize: 18,
          fontWeight: 600,
          color: "var(--fg-primary)",
        }}
      >
        1. Объект
      </h2>

      {/* HeadlineBar — verdict */}
      <div style={{ marginBottom: 16 }}>
        <HeadlineBar title={headlineTitle} subtitle={headlineSubtitle} />
      </div>

      {/* KPI row — 4 cards */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))",
          gap: 12,
          marginBottom: 20,
        }}
      >
        <KpiCard value={areaHa} label="Площадь" color="neutral" />
        <KpiCard value={district} label="Район" color="neutral" />
        <KpiCard value={medianPrice} label="Медиана рынка" color="blue" />
        <KpiCard value={scoreStr} label="Инвест-балл" color={scoreColor} />
      </div>

      {/* 2-column grid: map (left) + EGRN + POI (right) */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "400px 1fr",
          gap: 16,
          alignItems: "start",
          marginBottom: 20,
        }}
      >
        {/* Left: mini-map */}
        <MiniMap data={data} />

        {/* Right: EGRN table + POI list */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <EgrnPropertyTable data={egrn} />

          {poiData ? (
            <PoiList2Gis
              items={poiData.items}
              totalScore={poiData.poi_weighted_score}
            />
          ) : (
            // Fallback: build from analyze score_breakdown
            <PoiList2Gis
              items={Object.entries(data.score_breakdown).flatMap(
                ([cat, pois]) =>
                  pois.slice(0, 2).map((poi) => ({
                    category: cat,
                    name: poi.name ?? cat,
                    distance_m: poi.distance_m,
                    weight: 0.1,
                    score_contribution: 5,
                  })),
              )}
              totalScore={data.score}
            />
          )}
        </div>
      </div>

      {/* Export buttons */}
      <div
        style={{
          paddingTop: 16,
          borderTop: "1px solid var(--border-soft)",
        }}
      >
        <ExportButtons cad={cad} analyzeData={data} />
      </div>
    </section>
  );
}
