"use client";

import type { ChangeEvent } from "react";
import type {
  ParcelBboxFilters,
  ParcelStatus,
  ParcelVri,
} from "@/lib/site-finder-api";

interface MapFilterBarProps {
  filters: ParcelBboxFilters;
  onChange: (filters: ParcelBboxFilters) => void;
  totalCount: number;
  matchCount: number;
}

interface ChipProps {
  label: string;
  selected: boolean;
  onClick: () => void;
  disabled?: boolean;
  title?: string;
}

function Chip({ label, selected, onClick, disabled, title }: ChipProps) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      title={title}
      style={{
        padding: "4px 12px",
        borderRadius: 999,
        border: selected
          ? "1px solid var(--accent)"
          : "1px solid var(--border-card)",
        background: selected ? "var(--accent-soft)" : "var(--bg-card)",
        color: selected ? "var(--accent)" : "var(--fg-secondary)",
        fontSize: 12,
        fontWeight: selected ? 500 : 400,
        cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.45 : 1,
        whiteSpace: "nowrap",
        transition: "background 0.12s, color 0.12s, border-color 0.12s",
      }}
    >
      {label}
    </button>
  );
}

// B1 by-bbox payload doesn't carry district/vri yet, and the endpoint ignores
// those query params — every parcel is adapted with placeholders
// (district:"—" / vri:"other"), so filtering on them either wipes the map or
// silently does nothing (#1475). Keep the controls visible but disabled until
// enrichment lands, so the UI doesn't pretend 2 of 3 filter axes work.
const DISTRICT_VRI_FILTERS_AVAILABLE = false;
const DISTRICT_VRI_DISABLED_HINT =
  "Фильтр по району / ВРИ появится после обогащения данных участков";

const DISTRICTS = [
  "Ленинский",
  "Верх-Исетский",
  "Орджоникидзевский",
  "Чкаловский",
  "Кировский",
  "Октябрьский",
];

const VRI_OPTIONS: Array<{ value: ParcelVri; label: string }> = [
  { value: "multistory", label: "МКД" },
  { value: "mixed", label: "Смешанный" },
  { value: "individual", label: "ИЖС" },
  { value: "office", label: "Офисный" },
];

const AREA_OPTIONS: Array<{
  label: string;
  min?: number;
  max?: number;
}> = [
  { label: "до 0.5 га", max: 0.5 },
  { label: "0.5–1 га", min: 0.5, max: 1 },
  { label: "1–3 га", min: 1, max: 3 },
  { label: "от 3 га", min: 3 },
];

export function MapFilterBar({
  filters,
  onChange,
  totalCount,
  matchCount,
}: MapFilterBarProps) {
  function toggleStatus(s: ParcelStatus) {
    onChange({ ...filters, status: filters.status === s ? undefined : s });
  }

  function toggleDistrict(d: string) {
    onChange({
      ...filters,
      district: filters.district === d ? undefined : d,
    });
  }

  function toggleVri(v: ParcelVri) {
    if (!DISTRICT_VRI_FILTERS_AVAILABLE) return;
    onChange({ ...filters, vri: filters.vri === v ? undefined : v });
  }

  function toggleArea(min?: number, max?: number) {
    const same = filters.min_area === min && filters.max_area === max;
    onChange({
      ...filters,
      min_area: same ? undefined : min,
      max_area: same ? undefined : max,
    });
  }

  function clearAll() {
    onChange({});
  }

  const hasFilters =
    filters.status != null ||
    (DISTRICT_VRI_FILTERS_AVAILABLE && filters.district != null) ||
    (DISTRICT_VRI_FILTERS_AVAILABLE && filters.vri != null) ||
    filters.min_area != null ||
    filters.max_area != null;

  return (
    <div
      style={{
        background: "var(--bg-card)",
        borderBottom: "1px solid var(--border-card)",
        padding: "8px 16px",
        display: "flex",
        flexWrap: "wrap",
        alignItems: "center",
        gap: 8,
      }}
    >
      {/* Counter */}
      <span
        style={{
          fontSize: 12,
          color: "var(--fg-secondary)",
          marginRight: 4,
          flexShrink: 0,
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {matchCount.toLocaleString("ru")} / {totalCount.toLocaleString("ru")}{" "}
        участков
      </span>

      {/* Status chips */}
      <Chip
        label="Свободные"
        selected={filters.status === "free"}
        onClick={() => toggleStatus("free")}
      />
      <Chip
        label="В работе"
        selected={filters.status === "in_progress"}
        onClick={() => toggleStatus("in_progress")}
      />
      <Chip
        label="Избранные"
        selected={filters.status === "favorite"}
        onClick={() => toggleStatus("favorite")}
      />

      {/* Separator */}
      <span
        style={{
          width: 1,
          height: 20,
          background: "var(--border-soft)",
          flexShrink: 0,
        }}
      />

      {/* Area chips */}
      {AREA_OPTIONS.map((opt) => (
        <Chip
          key={opt.label}
          label={opt.label}
          selected={
            filters.min_area === opt.min && filters.max_area === opt.max
          }
          onClick={() => toggleArea(opt.min, opt.max)}
        />
      ))}

      {/* Separator */}
      <span
        style={{
          width: 1,
          height: 20,
          background: "var(--border-soft)",
          flexShrink: 0,
        }}
      />

      {/* VRI chips — disabled until B1 enrichment returns vri (#1475) */}
      {VRI_OPTIONS.map((opt) => (
        <Chip
          key={opt.value}
          label={opt.label}
          selected={
            DISTRICT_VRI_FILTERS_AVAILABLE && filters.vri === opt.value
          }
          onClick={() => toggleVri(opt.value)}
          disabled={!DISTRICT_VRI_FILTERS_AVAILABLE}
          title={
            DISTRICT_VRI_FILTERS_AVAILABLE ? undefined : DISTRICT_VRI_DISABLED_HINT
          }
        />
      ))}

      {/* Separator */}
      <span
        style={{
          width: 1,
          height: 20,
          background: "var(--border-soft)",
          flexShrink: 0,
        }}
      />

      {/* District selector — disabled until B1 enrichment returns district (#1475) */}
      <select
        value={DISTRICT_VRI_FILTERS_AVAILABLE ? (filters.district ?? "") : ""}
        disabled={!DISTRICT_VRI_FILTERS_AVAILABLE}
        title={
          DISTRICT_VRI_FILTERS_AVAILABLE
            ? undefined
            : DISTRICT_VRI_DISABLED_HINT
        }
        onChange={(e: ChangeEvent<HTMLSelectElement>) =>
          onChange({ ...filters, district: e.target.value || undefined })
        }
        style={{
          fontSize: 12,
          padding: "4px 8px",
          borderRadius: 999,
          border:
            DISTRICT_VRI_FILTERS_AVAILABLE && filters.district
              ? "1px solid var(--accent)"
              : "1px solid var(--border-card)",
          background:
            DISTRICT_VRI_FILTERS_AVAILABLE && filters.district
              ? "var(--accent-soft)"
              : "var(--bg-card)",
          color:
            DISTRICT_VRI_FILTERS_AVAILABLE && filters.district
              ? "var(--accent)"
              : "var(--fg-secondary)",
          cursor: DISTRICT_VRI_FILTERS_AVAILABLE ? "pointer" : "not-allowed",
          opacity: DISTRICT_VRI_FILTERS_AVAILABLE ? 1 : 0.45,
        }}
      >
        <option value="">Все районы</option>
        {DISTRICTS.map((d) => (
          <option key={d} value={d}>
            {d}
          </option>
        ))}
      </select>

      {/* Clear all */}
      {hasFilters && (
        <button
          onClick={clearAll}
          style={{
            fontSize: 12,
            color: "var(--danger)",
            background: "none",
            border: "none",
            cursor: "pointer",
            padding: "4px 8px",
            textDecoration: "underline",
          }}
        >
          Сбросить
        </button>
      )}
    </div>
  );
}
