"use client";

/**
 * Concept (Generative Design) — Stage 1d UI.
 *
 * Flow: define the parcel boundary (draw a polygon OR resolve from a cadastre
 * number) → set ConceptInput parameters → POST /api/v1/concepts → render the
 * returned variants (placement map + ТЭП + financial model + export).
 *
 * Contract: backend/app/schemas/concept.py (ConceptInput / ConceptOutput).
 * Map is lazy-mounted (Leaflet uses `window`); data-fetching via TanStack
 * useMutation through the shared apiFetch.
 */

import dynamic from "next/dynamic";
import Link from "next/link";
import { useState } from "react";
import { MapPin, Pencil } from "lucide-react";
import type { Polygon } from "geojson";

import { CadInput } from "@/components/site-finder/CadInput";
import { Section } from "@/components/analytics/Section";
import {
  ConceptParamsForm,
  DEFAULT_PARAMS,
  type ConceptParams,
} from "@/components/concept/ConceptParamsForm";
import { ConceptVariantsResult } from "@/components/concept/ConceptVariantsResult";
import {
  HouseProgramPicker,
  type ProgramMode,
} from "@/components/concept/HouseProgramPicker";
import {
  polygonAreaSqm,
  useCadastreGeom,
  useCreateConcept,
  type BuildingProgramItem,
} from "@/lib/concept-api";

// ConceptDrawMap uses Leaflet + leaflet-draw — must load without SSR.
const ConceptDrawMap = dynamic(
  () =>
    import("@/components/concept/ConceptDrawMap").then((m) => m.ConceptDrawMap),
  {
    ssr: false,
    loading: () => (
      <div
        style={{
          height: 420,
          background: "var(--bg-card-alt)",
          border: "1px dashed var(--border-strong)",
          borderRadius: 12,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: "var(--fg-tertiary)",
          fontSize: 14,
        }}
      >
        Загрузка карты…
      </div>
    ),
  },
);

type InputMode = "draw" | "cadastre";

const ha = (sqm: number) =>
  (sqm / 10_000).toLocaleString("ru-RU", {
    maximumFractionDigits: 2,
  });

export default function ConceptPage() {
  const [mode, setMode] = useState<InputMode>("draw");
  const [polygon, setPolygon] = useState<Polygon | null>(null);
  const [params, setParams] = useState<ConceptParams>(DEFAULT_PARAMS);

  // Stage 3b (#1965): program mode — «Авто (max-FAR)» vs «Выбрать дома».
  const [programMode, setProgramMode] = useState<ProgramMode>("auto");
  const [houseProgram, setHouseProgram] = useState<BuildingProgramItem[]>([]);

  const cadastreGeom = useCadastreGeom();
  const concept = useCreateConcept();

  // Any change to the parcel boundary invalidates a previous concept run:
  // its variants/ТЭП/financials were computed for the OLD parcel, so showing
  // them against the new outline would be inconsistent.
  function handlePolygonChange(next: Polygon | null) {
    setPolygon(next);
    if (concept.data || concept.isError) {
      concept.reset();
    }
  }

  function handleCadSubmit(cad: string) {
    cadastreGeom.mutate(cad, {
      onSuccess: (geom) => {
        handlePolygonChange(geom);
      },
    });
  }

  function handleGenerate() {
    if (!polygon) return;
    // «Выбрать дома» с непустой программой → building_program (бэк кладёт ровно
    // её). Иначе omit → жадная max-FAR раскладка (поведение по умолчанию).
    const program =
      programMode === "pick" && houseProgram.length > 0
        ? houseProgram
        : undefined;
    concept.mutate({
      parcel_geojson: polygon,
      housing_class: params.housing_class,
      target_floors: params.target_floors,
      development_type: params.development_type,
      land_cost_rub: params.land_cost_rub,
      building_program: program,
    });
  }

  const parcelAreaSqm = polygon ? polygonAreaSqm(polygon) : 0;

  return (
    <main style={{ minHeight: "100vh", background: "var(--bg-app)" }}>
      {/* Header */}
      <header
        style={{
          background: "var(--bg-card)",
          borderBottom: "1px solid var(--border-card)",
          padding: "12px 24px",
          display: "flex",
          alignItems: "center",
          gap: 16,
        }}
      >
        <Link
          href="/"
          style={{
            fontSize: 13,
            color: "var(--fg-secondary)",
            textDecoration: "none",
          }}
        >
          ← Главная
        </Link>
        <span style={{ color: "var(--border-soft)" }}>·</span>
        <h1
          style={{
            margin: 0,
            fontSize: 16,
            fontWeight: 600,
            color: "var(--fg-primary)",
          }}
        >
          Концепция застройки · генеративный дизайн
        </h1>
      </header>

      <div
        style={{ maxWidth: 1280, margin: "0 auto", padding: "16px 24px 48px" }}
      >
        <p
          style={{
            margin: "0 0 16px",
            fontSize: 13,
            color: "var(--fg-secondary)",
            maxWidth: 760,
          }}
        >
          Задайте границы участка и параметры проекта — движок предложит три
          стратегии размещения застройки с расчётом ТЭП и финансовой модели.
        </p>

        {/* Input row: parcel boundary (left) + parameters (right) */}
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "minmax(0, 1fr) 320px",
            gap: 16,
            alignItems: "start",
          }}
        >
          {/* Parcel boundary */}
          <Section
            title="Границы участка"
            subtitle="Нарисуйте полигон на карте или укажите кадастровый номер."
            right={
              <div
                role="tablist"
                aria-label="Способ ввода участка"
                style={{ display: "flex", gap: 4 }}
              >
                <ModeTab
                  active={mode === "draw"}
                  onClick={() => setMode("draw")}
                  icon={<Pencil size={14} strokeWidth={1.5} />}
                  label="Нарисовать"
                />
                <ModeTab
                  active={mode === "cadastre"}
                  onClick={() => setMode("cadastre")}
                  icon={<MapPin size={14} strokeWidth={1.5} />}
                  label="Кадастр"
                />
              </div>
            }
          >
            {mode === "cadastre" && (
              <div style={{ marginBottom: 12 }}>
                <CadInput
                  onSubmit={handleCadSubmit}
                  loading={cadastreGeom.isPending}
                />
                {cadastreGeom.isError && (
                  <p
                    style={{
                      margin: "8px 0 0",
                      fontSize: 12,
                      color: "var(--danger)",
                    }}
                    role="alert"
                  >
                    {cadastreGeom.error.message}
                  </p>
                )}
              </div>
            )}

            <ConceptDrawMap polygon={polygon} onChange={handlePolygonChange} />

            <div
              style={{
                marginTop: 12,
                fontSize: 13,
                color: polygon ? "var(--fg-primary)" : "var(--fg-tertiary)",
              }}
            >
              {polygon
                ? `Участок задан · площадь ≈ ${ha(parcelAreaSqm)} га`
                : "Участок не задан."}
            </div>
          </Section>

          {/* Parameters */}
          <Section
            title="Параметры проекта"
            subtitle="Класс, тип застройки и этажность. Можно задать программу из типовых домов вместо авторазмещения."
          >
            <div style={{ display: "grid", gap: 16 }}>
              <HouseProgramPicker
                mode={programMode}
                onModeChange={setProgramMode}
                program={houseProgram}
                onChange={setHouseProgram}
                isPending={concept.isPending}
              />
              <ConceptParamsForm
                params={params}
                onChange={setParams}
                onSubmit={handleGenerate}
                hasPolygon={polygon != null}
                isPending={concept.isPending}
              />
            </div>
          </Section>
        </div>

        {/* Results */}
        {concept.isError && (
          <Section title="Варианты застройки">
            <p
              style={{ margin: 0, fontSize: 13, color: "var(--danger)" }}
              role="alert"
            >
              Не удалось рассчитать концепции: {concept.error.message}
            </p>
          </Section>
        )}

        {concept.isPending && (
          <Section title="Варианты застройки">
            <p
              style={{ margin: 0, fontSize: 13, color: "var(--fg-secondary)" }}
            >
              Движок рассчитывает варианты размещения…
            </p>
          </Section>
        )}

        {concept.isSuccess && polygon && (
          <div style={{ marginTop: 24 }}>
            <ConceptVariantsResult
              parcel={polygon}
              variants={concept.data.variants}
            />
          </div>
        )}
      </div>
    </main>
  );
}

// ── Input-mode tab ────────────────────────────────────────────────────────────

interface ModeTabProps {
  active: boolean;
  onClick: () => void;
  icon: React.ReactNode;
  label: string;
}

function ModeTab({ active, onClick, icon, label }: ModeTabProps) {
  return (
    <button
      type="button"
      role="tab"
      aria-selected={active}
      onClick={onClick}
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        padding: "6px 12px",
        height: 32,
        background: active ? "var(--accent-soft)" : "transparent",
        color: active ? "var(--accent)" : "var(--fg-secondary)",
        border: active
          ? "1px solid var(--accent-soft)"
          : "1px solid var(--border-card)",
        borderRadius: 6,
        fontSize: 13,
        fontWeight: 500,
        cursor: "pointer",
      }}
    >
      {icon}
      {label}
    </button>
  );
}
