"use client";

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

import { CompareTable } from "@/components/site-finder/compare/CompareTable";
import type { CompareColumn } from "@/components/site-finder/compare/CompareTable";
import { ParcelCompareLoader } from "@/components/site-finder/compare/ParcelCompareLoader";
import {
  COMPARE_MAX,
  COMPARE_MIN,
  getShortlist,
  isValidCad,
  saveShortlist,
} from "@/lib/compare-shortlist";

export default function ComparePage() {
  // Shortlist of cads. Hydrated from localStorage after mount (SSR-safe: the
  // first client render matches the server's empty list, then the effect fills
  // it — avoids a hydration mismatch).
  const [shortlist, setShortlist] = useState<string[]>([]);
  const [hydrated, setHydrated] = useState(false);
  const [input, setInput] = useState("");
  const [inputError, setInputError] = useState<string | null>(null);

  // Per-cad column state, keyed by cad. Lifted up from each ParcelCompareLoader.
  const [columns, setColumns] = useState<Record<string, CompareColumn>>({});

  useEffect(() => {
    setShortlist(getShortlist());
    setHydrated(true);
  }, []);

  // Persist to localStorage on every change (after hydration so the initial
  // empty state never clobbers a saved list).
  useEffect(() => {
    if (hydrated) saveShortlist(shortlist);
  }, [shortlist, hydrated]);

  const handleResult = useCallback((col: CompareColumn) => {
    setColumns((prev) => {
      const existing = prev[col.cad];
      // Avoid a needless state update (and re-render loop) when nothing changed.
      if (
        existing &&
        existing.status === col.status &&
        existing.errorMsg === col.errorMsg &&
        existing.districtName === col.districtName &&
        existing.verdictLabel === col.verdictLabel &&
        existing.score === col.score &&
        existing.scoreLabel === col.scoreLabel &&
        existing.velocityScore === col.velocityScore &&
        existing.velocityDataAvailable === col.velocityDataAvailable &&
        existing.medianPricePerM2 === col.medianPricePerM2 &&
        existing.pipeline24mo === col.pipeline24mo &&
        existing.confidenceLabel === col.confidenceLabel &&
        existing.confidenceValue === col.confidenceValue
      ) {
        return prev;
      }
      return { ...prev, [col.cad]: col };
    });
  }, []);

  function addCad(e: React.FormEvent) {
    e.preventDefault();
    const cad = input.trim();
    if (!isValidCad(cad)) {
      setInputError("Неверный формат. Ожидается 66:41:0204016:10 или 66:41:0204016.");
      return;
    }
    if (shortlist.includes(cad)) {
      setInputError("Этот участок уже в сравнении.");
      return;
    }
    if (shortlist.length >= COMPARE_MAX) {
      setInputError(`Можно сравнить не более ${COMPARE_MAX} участков.`);
      return;
    }
    setShortlist((prev) => [...prev, cad]);
    setInput("");
    setInputError(null);
  }

  const removeCad = useCallback((cad: string) => {
    setShortlist((prev) => prev.filter((c) => c !== cad));
    setColumns((prev) => {
      const next = { ...prev };
      delete next[cad];
      return next;
    });
  }, []);

  // Build ordered columns from the shortlist; default to a loading column so
  // the table renders immediately while each loader resolves.
  const orderedColumns: CompareColumn[] = useMemo(
    () =>
      shortlist.map(
        (cad) => columns[cad] ?? { cad, status: "loading" as const },
      ),
    [shortlist, columns],
  );

  const canCompare = shortlist.length >= COMPARE_MIN;

  return (
    <main
      style={{
        minHeight: "100vh",
        background: "var(--bg-app)",
        padding: "24px 20px",
      }}
    >
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        {/* Header */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            fontSize: 13,
            color: "var(--fg-secondary)",
          }}
        >
          <Link
            href="/site-finder"
            style={{
              color: "var(--accent)",
              textDecoration: "none",
              fontWeight: 500,
            }}
          >
            Site Finder
          </Link>
          <span style={{ color: "var(--fg-tertiary)" }}>/</span>
          <span style={{ color: "var(--fg-tertiary)" }}>сравнение участков</span>
        </div>

        <h1
          style={{
            margin: "8px 0 4px",
            fontSize: 22,
            fontWeight: 600,
            color: "var(--fg-primary)",
          }}
        >
          Сравнение участков
        </h1>
        <p
          style={{
            margin: "0 0 20px",
            color: "var(--fg-secondary)",
            fontSize: 13,
          }}
        >
          Добавьте от {COMPARE_MIN} до {COMPARE_MAX} кадастровых номеров — метрики
          анализа (вердикт МКД, инвест-балл, скорость продаж, цена, пайплайн)
          встанут рядом. Лучшее значение в строке подсвечено. Список сохраняется
          между сессиями.
        </p>

        {/* Add form */}
        <form
          onSubmit={addCad}
          style={{ display: "flex", gap: 8, alignItems: "flex-start" }}
        >
          <div style={{ flex: 1, maxWidth: 420 }}>
            <input
              type="text"
              value={input}
              onChange={(e) => {
                setInput(e.target.value);
                setInputError(null);
              }}
              placeholder="66:41:0204016:10"
              aria-label="Кадастровый номер для сравнения"
              disabled={shortlist.length >= COMPARE_MAX}
              style={{
                width: "100%",
                padding: "8px 12px",
                fontSize: 14,
                fontFamily: "monospace",
                border: inputError
                  ? "1px solid var(--danger)"
                  : "1px solid var(--border-strong)",
                borderRadius: 8,
                outline: "none",
                background: "var(--bg-card)",
              }}
            />
            {inputError ? (
              <p
                style={{
                  margin: "6px 0 0",
                  fontSize: 12,
                  color: "var(--danger)",
                }}
              >
                {inputError}
              </p>
            ) : null}
          </div>
          <button
            type="submit"
            disabled={!input.trim() || shortlist.length >= COMPARE_MAX}
            style={{
              padding: "8px 18px",
              fontSize: 14,
              fontWeight: 600,
              background:
                !input.trim() || shortlist.length >= COMPARE_MAX
                  ? "var(--fg-tertiary)"
                  : "var(--accent)",
              color: "var(--fg-on-dark)",
              border: "none",
              borderRadius: 8,
              cursor:
                !input.trim() || shortlist.length >= COMPARE_MAX
                  ? "default"
                  : "pointer",
              whiteSpace: "nowrap",
            }}
          >
            Добавить
          </button>
        </form>

        {/* Headless loaders — one per cad, lift analyze metrics up */}
        {shortlist.map((cad) => (
          <ParcelCompareLoader key={cad} cad={cad} onResult={handleResult} />
        ))}

        {/* Body */}
        <div
          style={{
            marginTop: 24,
            background: "var(--bg-card)",
            border: "1px solid var(--border-card)",
            borderRadius: 12,
            padding: 20,
          }}
        >
          {!canCompare ? (
            <div
              style={{
                padding: "32px 24px",
                textAlign: "center",
                color: "var(--fg-tertiary)",
                fontSize: 14,
              }}
            >
              {shortlist.length === 0
                ? "Список пуст. Добавьте участки выше, чтобы начать сравнение."
                : `Добавьте ещё минимум ${COMPARE_MIN - shortlist.length} участок для сравнения.`}
            </div>
          ) : (
            <CompareTable columns={orderedColumns} onRemove={removeCad} />
          )}
        </div>
      </div>
    </main>
  );
}
