"use client";

/**
 * SaleShareControls — порог % (слайдер + гистограмма распределения) и фильтры.
 * Controlled: всё состояние живёт в page.tsx, сюда приходит через props.
 */
import type { SaleShareSort, SaleShareSummary } from "@/types/sale-share";
import { heatColor, houseTypeLabel } from "./saleShareUtils";

const SORT_OPTIONS: Array<{ value: SaleShareSort; label: string }> = [
  { value: "share_desc", label: "Доля в продаже ↓" },
  { value: "active_desc", label: "Кол-во в продаже ↓" },
  { value: "exposure_desc", label: "Срок экспозиции ↓" },
  { value: "price_asc", label: "Цена ↑" },
  { value: "price_desc", label: "Цена ↓" },
];

/** Верхняя граница корзины: "10-20" → 20, "100+" → Infinity. */
function bucketUpperBound(label: string): number {
  if (label.endsWith("+")) return Infinity;
  const parts = label.split("-");
  return parts.length === 2 ? Number(parts[1]) : Infinity;
}

/** Нижняя граница корзины (для выбора цвета): "10-20" → 10, "100+" → 100. */
function bucketLowerBound(label: string): number {
  const m = label.match(/^(\d+)/);
  return m ? Number(m[1]) : 0;
}

interface HistogramProps {
  summary: SaleShareSummary | undefined;
  minPct: number;
}

function Histogram({ summary, minPct }: HistogramProps) {
  if (!summary || summary.histogram.length === 0) return null;
  const maxCount = Math.max(1, ...summary.histogram.map((b) => b.count));
  return (
    <div className="ss-hist" role="img" aria-label="Распределение домов по доле квартир в продаже">
      {summary.histogram.map((b) => {
        const inRange = bucketUpperBound(b.bucket) > minPct;
        const h = Math.round((b.count / maxCount) * 100);
        return (
          <div className="ss-hist-col" key={b.bucket} title={`${b.bucket}% — ${b.count} домов`}>
            <span className="ss-hist-count">{b.count}</span>
            <span className="ss-hist-track">
              <span
                className="ss-hist-bar"
                style={{
                  height: `${Math.max(b.count > 0 ? 4 : 0, h)}%`,
                  background: heatColor(bucketLowerBound(b.bucket) + 0.5),
                  opacity: inRange ? 1 : 0.28,
                }}
              />
            </span>
            <span className="ss-hist-label">{b.bucket}</span>
          </div>
        );
      })}
    </div>
  );
}

interface Props {
  summary: SaleShareSummary | undefined;
  minPct: number;
  onMinPct: (v: number) => void;
  city: string;
  onCity: (v: string) => void;
  priceMin: string;
  onPriceMin: (v: string) => void;
  priceMax: string;
  onPriceMax: (v: string) => void;
  yearMin: string;
  onYearMin: (v: string) => void;
  yearMax: string;
  onYearMax: (v: string) => void;
  houseType: string;
  onHouseType: (v: string) => void;
  houseTypeOptions: string[];
  sort: SaleShareSort;
  onSort: (v: SaleShareSort) => void;
  window: "now" | "45d";
  onWindow: (v: "now" | "45d") => void;
  minCount: number;
  onMinCount: (v: number) => void;
}

export function SaleShareControls({
  summary,
  minPct,
  onMinPct,
  city,
  onCity,
  priceMin,
  onPriceMin,
  priceMax,
  onPriceMax,
  yearMin,
  onYearMin,
  yearMax,
  onYearMax,
  houseType,
  onHouseType,
  houseTypeOptions,
  sort,
  onSort,
  window,
  onWindow,
  minCount,
  onMinCount,
}: Props) {
  const sliderMax =
    summary && summary.max_pct != null
      ? Math.max(10, Math.ceil(summary.max_pct))
      : 50;

  return (
    <article className="card">
      <div className="card-head">
        <div>
          <div className="section-kicker">Порог и фильтры</div>
          <h2>Доля квартир дома в продаже ≥ {minPct}%</h2>
        </div>
      </div>

      <div className="card-body">
        <div className="ss-window-row">
          <span id="ss-window-label" className="ss-window-label">
            Окно метрики
          </span>
          <div className="ss-seg" role="group" aria-labelledby="ss-window-label">
            <button
              type="button"
              className={`ss-seg-btn${window === "now" ? " is-active" : ""}`}
              aria-pressed={window === "now"}
              onClick={() => onWindow("now")}
            >
              Сейчас
            </button>
            <button
              type="button"
              className={`ss-seg-btn${window === "45d" ? " is-active" : ""}`}
              aria-pressed={window === "45d"}
              onClick={() => onWindow("45d")}
            >
              За 45 дней
            </button>
          </div>
        </div>

        <Histogram summary={summary} minPct={minPct} />

        <div className="ss-slider-row">
          <label htmlFor="ss-minpct" className="ss-slider-label">
            Порог доли, %
          </label>
          <input
            id="ss-minpct"
            type="range"
            min={0}
            max={sliderMax}
            step={1}
            value={Math.min(minPct, sliderMax)}
            onChange={(e) => onMinPct(Number(e.target.value))}
            className="ss-slider"
            aria-valuetext={`${minPct}%`}
          />
          <output className="ss-slider-out" htmlFor="ss-minpct">
            {minPct}%
          </output>
        </div>

        <div className="ss-filters">
          <div className="ss-field">
            <label htmlFor="ss-city">Город</label>
            <input
              id="ss-city"
              type="text"
              value={city}
              onChange={(e) => onCity(e.target.value)}
              placeholder="Екатеринбург"
            />
          </div>
          <div className="ss-field">
            <label htmlFor="ss-price-min">Цена от, ₽</label>
            <input
              id="ss-price-min"
              type="number"
              inputMode="numeric"
              min={0}
              value={priceMin}
              onChange={(e) => onPriceMin(e.target.value)}
              placeholder="—"
            />
          </div>
          <div className="ss-field">
            <label htmlFor="ss-price-max">Цена до, ₽</label>
            <input
              id="ss-price-max"
              type="number"
              inputMode="numeric"
              min={0}
              value={priceMax}
              onChange={(e) => onPriceMax(e.target.value)}
              placeholder="—"
            />
          </div>
          <div className="ss-field">
            <label htmlFor="ss-year-min">Год от</label>
            <input
              id="ss-year-min"
              type="number"
              inputMode="numeric"
              min={1800}
              max={2100}
              value={yearMin}
              onChange={(e) => onYearMin(e.target.value)}
              placeholder="—"
            />
          </div>
          <div className="ss-field">
            <label htmlFor="ss-year-max">Год до</label>
            <input
              id="ss-year-max"
              type="number"
              inputMode="numeric"
              min={1800}
              max={2100}
              value={yearMax}
              onChange={(e) => onYearMax(e.target.value)}
              placeholder="—"
            />
          </div>
          <div className="ss-field">
            <label htmlFor="ss-house-type">Тип дома</label>
            <select
              id="ss-house-type"
              value={houseType}
              onChange={(e) => onHouseType(e.target.value)}
            >
              <option value="">Любой</option>
              {houseTypeOptions.map((t) => (
                <option key={t} value={t}>
                  {houseTypeLabel(t)}
                </option>
              ))}
            </select>
          </div>
          <div className="ss-field">
            <label htmlFor="ss-min-count">Мин. объявлений в доме</label>
            <input
              id="ss-min-count"
              type="number"
              inputMode="numeric"
              min={0}
              step={1}
              value={minCount === 0 ? "" : minCount}
              onChange={(e) => {
                const n = Math.floor(Number(e.target.value));
                onMinCount(Number.isFinite(n) && n > 0 ? n : 0);
              }}
              placeholder="0"
            />
          </div>
          <div className="ss-field">
            <label htmlFor="ss-sort">Сортировка</label>
            <select
              id="ss-sort"
              value={sort}
              onChange={(e) => onSort(e.target.value as SaleShareSort)}
            >
              {SORT_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>
    </article>
  );
}
