"use client";

/**
 * HouseProgramPicker — Stage 3b (#1965, эпик #1953).
 *
 * Lets the user pick WHAT to build instead of the auto max-FAR buildout:
 *   • «Авто (max-FAR)» (default) — building_program omitted → backend keeps its
 *     greedy 3-strategy placement (unchanged behaviour).
 *   • «Выбрать дома» — the user adds typical house types from the catalog
 *     (GET /concepts/house-types), each with a count (1–50) and floors (1–40,
 *     default from the catalog). The component builds the
 *     `building_program: [{section_type, floors, count}, …]` and lifts it to the
 *     parent via `onChange`; auto mode lifts `null`.
 *
 * The catalog is the single source of truth — footprint / default floors / class
 * are shown as helper text straight from the backend (no frontend hardcode).
 */

import { Plus, Trash2 } from "lucide-react";

import {
  HOUSING_CLASS_LABELS,
  useHouseTypes,
  type BuildingProgramItem,
  type HouseTypeCatalogItem,
} from "@/lib/concept-api";

// Contract bounds (mirror BuildingProgramItem in the backend schema).
const FLOORS_MIN = 1;
const FLOORS_MAX = 40;
const COUNT_MIN = 1;
const COUNT_MAX = 50;

export type ProgramMode = "auto" | "pick";

const nf = new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 0 });

const labelStyle: React.CSSProperties = {
  display: "block",
  fontSize: 12,
  fontWeight: 500,
  textTransform: "uppercase",
  letterSpacing: "0.04em",
  color: "var(--fg-secondary)",
  marginBottom: 6,
};

const controlStyle: React.CSSProperties = {
  width: "100%",
  padding: "8px 12px",
  fontSize: 14,
  border: "1px solid var(--border-strong)",
  borderRadius: 8,
  outline: "none",
  background: "var(--bg-card)",
  color: "var(--fg-primary)",
};

interface Props {
  mode: ProgramMode;
  onModeChange: (mode: ProgramMode) => void;
  /** Selected program rows (pick mode). Owned by the parent; lifted via onChange. */
  program: BuildingProgramItem[];
  onChange: (program: BuildingProgramItem[]) => void;
  /** Disables controls while a calculation is in flight. */
  isPending: boolean;
}

function clampInt(
  raw: number,
  min: number,
  max: number,
  fallback: number,
): number {
  if (!Number.isFinite(raw)) return fallback;
  return Math.min(max, Math.max(min, Math.round(raw)));
}

export function HouseProgramPicker({
  mode,
  onModeChange,
  program,
  onChange,
  isPending,
}: Props) {
  const houseTypes = useHouseTypes();
  const catalog = houseTypes.data ?? [];

  function byKey(sectionType: string): HouseTypeCatalogItem | undefined {
    return catalog.find((ht) => ht.section_type === sectionType);
  }

  function addRow() {
    const first = catalog[0];
    if (!first) return;
    onChange([
      ...program,
      {
        section_type: first.section_type,
        floors: first.default_floors,
        count: 1,
      },
    ]);
  }

  function updateRow(index: number, patch: Partial<BuildingProgramItem>) {
    onChange(
      program.map((row, i) => (i === index ? { ...row, ...patch } : row)),
    );
  }

  function removeRow(index: number) {
    onChange(program.filter((_, i) => i !== index));
  }

  function handleTypeChange(index: number, sectionType: string) {
    // Switching the type resets floors to that type's catalog default (the
    // previous floors were tuned for a different house) but keeps the count.
    const ht = byKey(sectionType);
    updateRow(index, {
      section_type: sectionType,
      floors: ht ? ht.default_floors : program[index].floors,
    });
  }

  return (
    <div style={{ display: "grid", gap: 16 }}>
      {/* Mode toggle */}
      <div>
        <span style={labelStyle}>Что строить</span>
        <div
          role="tablist"
          aria-label="Режим программы застройки"
          style={{ display: "flex", gap: 4 }}
        >
          <ModeTab
            active={mode === "auto"}
            onClick={() => onModeChange("auto")}
            label="Авто (max-FAR)"
          />
          <ModeTab
            active={mode === "pick"}
            onClick={() => onModeChange("pick")}
            label="Выбрать дома"
          />
        </div>
        <p
          style={{
            margin: "8px 0 0",
            fontSize: 11,
            color: "var(--fg-tertiary)",
          }}
        >
          {mode === "auto"
            ? "Движок сам подберёт максимально плотную застройку в пределах нормативов (три стратегии)."
            : "Соберите программу из типовых домов — движок разместит ровно её и покажет, сколько секций поместилось."}
        </p>
      </div>

      {/* Pick mode: catalog program builder */}
      {mode === "pick" && (
        <div style={{ display: "grid", gap: 12 }}>
          {houseTypes.isPending && (
            <p
              style={{ margin: 0, fontSize: 13, color: "var(--fg-secondary)" }}
            >
              Загрузка каталога типовых домов…
            </p>
          )}

          {houseTypes.isError && (
            <p
              style={{ margin: 0, fontSize: 13, color: "var(--danger)" }}
              role="alert"
            >
              Не удалось загрузить каталог типовых домов:{" "}
              {houseTypes.error.message}
            </p>
          )}

          {houseTypes.isSuccess && (
            <>
              {program.length === 0 && (
                <p
                  style={{
                    margin: 0,
                    fontSize: 12,
                    color: "var(--fg-tertiary)",
                  }}
                >
                  Добавьте хотя бы один тип дома, чтобы задать программу. Пока
                  список пуст — будет использован авторежим.
                </p>
              )}

              {program.map((row, i) => {
                const ht = byKey(row.section_type);
                return (
                  <div
                    key={i}
                    style={{
                      border: "1px solid var(--border-card)",
                      borderRadius: 12,
                      padding: 12,
                      background: "var(--bg-card-alt)",
                    }}
                  >
                    <div
                      style={{
                        display: "grid",
                        gridTemplateColumns: "minmax(0, 1fr) 88px 88px 36px",
                        gap: 8,
                        alignItems: "end",
                      }}
                    >
                      {/* House type */}
                      <div>
                        <label htmlFor={`house-type-${i}`} style={labelStyle}>
                          Тип дома
                        </label>
                        <select
                          id={`house-type-${i}`}
                          value={row.section_type}
                          disabled={isPending}
                          onChange={(e) => handleTypeChange(i, e.target.value)}
                          style={controlStyle}
                        >
                          {catalog.map((opt) => (
                            <option
                              key={opt.section_type}
                              value={opt.section_type}
                            >
                              {opt.label_ru}
                            </option>
                          ))}
                        </select>
                      </div>

                      {/* Floors */}
                      <div>
                        <label htmlFor={`house-floors-${i}`} style={labelStyle}>
                          Этажей
                        </label>
                        <input
                          id={`house-floors-${i}`}
                          type="number"
                          min={FLOORS_MIN}
                          max={FLOORS_MAX}
                          value={row.floors}
                          disabled={isPending}
                          onChange={(e) =>
                            updateRow(i, {
                              floors: clampInt(
                                Number(e.target.value),
                                FLOORS_MIN,
                                FLOORS_MAX,
                                ht?.default_floors ?? FLOORS_MIN,
                              ),
                            })
                          }
                          style={controlStyle}
                        />
                      </div>

                      {/* Count */}
                      <div>
                        <label htmlFor={`house-count-${i}`} style={labelStyle}>
                          Секций
                        </label>
                        <input
                          id={`house-count-${i}`}
                          type="number"
                          min={COUNT_MIN}
                          max={COUNT_MAX}
                          value={row.count}
                          disabled={isPending}
                          onChange={(e) =>
                            updateRow(i, {
                              count: clampInt(
                                Number(e.target.value),
                                COUNT_MIN,
                                COUNT_MAX,
                                COUNT_MIN,
                              ),
                            })
                          }
                          style={controlStyle}
                        />
                      </div>

                      {/* Remove */}
                      <button
                        type="button"
                        onClick={() => removeRow(i)}
                        disabled={isPending}
                        aria-label="Удалить тип дома из программы"
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          justifyContent: "center",
                          height: 36,
                          width: 36,
                          background: "transparent",
                          border: "1px solid var(--border-card)",
                          borderRadius: 8,
                          color: "var(--fg-secondary)",
                          cursor: isPending ? "not-allowed" : "pointer",
                        }}
                      >
                        <Trash2 size={16} strokeWidth={1.5} />
                      </button>
                    </div>

                    {/* Catalog helper text — footprint / default floors / class */}
                    {ht && (
                      <p
                        style={{
                          margin: "8px 0 0",
                          fontSize: 11,
                          color: "var(--fg-tertiary)",
                        }}
                      >
                        Пятно секции {nf.format(ht.footprint_w_m)} ×{" "}
                        {nf.format(ht.footprint_d_m)} м ≈{" "}
                        {nf.format(ht.footprint_sqm)} м² · типовая этажность{" "}
                        {ht.default_floors} · класс{" "}
                        {HOUSING_CLASS_LABELS[ht.housing_class]}.
                      </p>
                    )}
                  </div>
                );
              })}

              <button
                type="button"
                onClick={addRow}
                disabled={isPending || catalog.length === 0}
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 8,
                  padding: "8px 14px",
                  height: 40,
                  background: "transparent",
                  border: "1px dashed var(--border-strong)",
                  borderRadius: 8,
                  color: "var(--accent)",
                  fontSize: 14,
                  fontWeight: 500,
                  cursor:
                    isPending || catalog.length === 0
                      ? "not-allowed"
                      : "pointer",
                }}
              >
                <Plus size={16} strokeWidth={1.5} />
                Добавить тип дома
              </button>
            </>
          )}
        </div>
      )}
    </div>
  );
}

// ── Mode tab ────────────────────────────────────────────────────────────────

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

function ModeTab({ active, onClick, 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",
      }}
    >
      {label}
    </button>
  );
}
