"use client";

import { useState } from "react";

import type {
  HouseType,
  RepairState,
  TradeInEstimateInput,
} from "@/types/trade-in";

const HOUSE_TYPE_LABELS: Record<HouseType, string> = {
  panel: "Панель",
  brick: "Кирпич",
  monolith: "Монолит",
  monolith_brick: "Монолит-кирпич",
  other: "Другое",
};

const REPAIR_STATE_LABELS: Record<RepairState, string> = {
  needs_repair: "Требует ремонта",
  standard: "Стандартный",
  good: "Хороший",
  excellent: "Евроремонт",
};

interface Props {
  onSubmit: (input: TradeInEstimateInput) => void;
  isPending: boolean;
  error: string | null;
}

interface FormState {
  address: string;
  area_m2: string;
  rooms: string;
  floor: string;
  total_floors: string;
  year_built: string;
  house_type: HouseType | "";
  repair_state: RepairState | "";
  has_balcony: boolean;
}

const INITIAL: FormState = {
  address: "",
  area_m2: "",
  rooms: "",
  floor: "",
  total_floors: "",
  year_built: "",
  house_type: "",
  repair_state: "",
  has_balcony: false,
};

function validate(f: FormState): string | null {
  if (f.address.trim().length < 3) return "Введите адрес (минимум 3 символа)";
  const area = Number(f.area_m2);
  if (!f.area_m2 || isNaN(area) || area <= 10 || area >= 500)
    return "Площадь: от 10 до 500 м²";
  const rooms = Number(f.rooms);
  if (f.rooms === "" || isNaN(rooms) || rooms < 0 || rooms > 10)
    return "Количество комнат: 0 (студия) — 10";
  const floor = Number(f.floor);
  if (!f.floor || isNaN(floor) || floor < 1 || floor > 100)
    return "Этаж: 1—100";
  const totalFloors = Number(f.total_floors);
  if (
    !f.total_floors ||
    isNaN(totalFloors) ||
    totalFloors < 1 ||
    totalFloors > 100
  )
    return "Этажей в доме: 1—100";
  if (floor > totalFloors) return "Этаж не может быть больше этажей в доме";
  if (f.year_built !== "") {
    const yr = Number(f.year_built);
    if (isNaN(yr) || yr < 1800 || yr > 2100) return "Год постройки: 1800—2100";
  }
  return null;
}

function toInput(f: FormState): TradeInEstimateInput {
  const input: TradeInEstimateInput = {
    address: f.address.trim(),
    area_m2: Number(f.area_m2),
    rooms: Number(f.rooms),
    floor: Number(f.floor),
    total_floors: Number(f.total_floors),
    has_balcony: f.has_balcony,
  };
  if (f.year_built !== "") input.year_built = Number(f.year_built);
  if (f.house_type !== "") input.house_type = f.house_type;
  if (f.repair_state !== "") input.repair_state = f.repair_state;
  return input;
}

export function EstimateForm({ onSubmit, isPending, error }: Props) {
  const [form, setForm] = useState<FormState>(INITIAL);
  const [touched, setTouched] = useState(false);

  const validationError = validate(form);
  const canSubmit = !validationError && !isPending;

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setTouched(true);
    if (!canSubmit) return;
    onSubmit(toInput(form));
  }

  function field<K extends keyof FormState>(key: K) {
    return (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
      setForm((prev) => ({ ...prev, [key]: e.target.value }));
    };
  }

  return (
    <form
      onSubmit={handleSubmit}
      style={{
        background: "#fff",
        border: "1px solid #e6e8ec",
        borderRadius: 12,
        padding: 20,
        display: "flex",
        flexDirection: "column",
        gap: 14,
      }}
    >
      <h2 style={{ margin: 0, fontSize: 18, color: "#1a1d23" }}>
        Параметры квартиры
      </h2>

      {/* Address */}
      <label>
        <span style={labelStyle}>
          Адрес <Required />
        </span>
        <input
          type="text"
          placeholder="ул. Ленина, 1, кв. 5, Екатеринбург"
          value={form.address}
          onChange={field("address")}
          minLength={3}
          maxLength={500}
          required
          style={inputStyle}
        />
      </label>

      {/* Area + Rooms row */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <label>
          <span style={labelStyle}>
            Площадь, м² <Required />
          </span>
          <input
            type="number"
            inputMode="decimal"
            placeholder="54"
            min={11}
            max={499}
            step={0.1}
            value={form.area_m2}
            onChange={field("area_m2")}
            required
            style={inputStyle}
          />
        </label>
        <label>
          <span style={labelStyle}>
            Комнат <Required />
          </span>
          <select
            value={form.rooms}
            onChange={field("rooms")}
            required
            style={inputStyle}
          >
            <option value="">— выбрать —</option>
            <option value="0">Студия</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5+</option>
          </select>
        </label>
      </div>

      {/* Floor + Total floors row */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <label>
          <span style={labelStyle}>
            Этаж <Required />
          </span>
          <input
            type="number"
            inputMode="numeric"
            placeholder="5"
            min={1}
            max={100}
            step={1}
            value={form.floor}
            onChange={field("floor")}
            required
            style={inputStyle}
          />
        </label>
        <label>
          <span style={labelStyle}>
            Этажей в доме <Required />
          </span>
          <input
            type="number"
            inputMode="numeric"
            placeholder="17"
            min={1}
            max={100}
            step={1}
            value={form.total_floors}
            onChange={field("total_floors")}
            required
            style={inputStyle}
          />
        </label>
      </div>

      {/* Year built */}
      <label>
        <span style={labelStyle}>Год постройки (опц.)</span>
        <input
          type="number"
          inputMode="numeric"
          placeholder="1985"
          min={1800}
          max={2100}
          step={1}
          value={form.year_built}
          onChange={field("year_built")}
          style={inputStyle}
        />
      </label>

      {/* House type */}
      <label>
        <span style={labelStyle}>Тип дома (опц.)</span>
        <select
          value={form.house_type}
          onChange={field("house_type")}
          style={inputStyle}
        >
          <option value="">— не указан —</option>
          {(Object.entries(HOUSE_TYPE_LABELS) as [HouseType, string][]).map(
            ([val, label]) => (
              <option key={val} value={val}>
                {label}
              </option>
            ),
          )}
        </select>
      </label>

      {/* Repair state */}
      <label>
        <span style={labelStyle}>Состояние ремонта (опц.)</span>
        <select
          value={form.repair_state}
          onChange={field("repair_state")}
          style={inputStyle}
        >
          <option value="">— не указано —</option>
          {(Object.entries(REPAIR_STATE_LABELS) as [RepairState, string][]).map(
            ([val, label]) => (
              <option key={val} value={val}>
                {label}
              </option>
            ),
          )}
        </select>
      </label>

      {/* Balcony */}
      <label
        style={{
          display: "flex",
          alignItems: "center",
          gap: 8,
          cursor: "pointer",
        }}
      >
        <input
          type="checkbox"
          checked={form.has_balcony}
          onChange={(e) =>
            setForm((prev) => ({ ...prev, has_balcony: e.target.checked }))
          }
          style={{ width: 16, height: 16, cursor: "pointer" }}
        />
        <span style={{ fontSize: 14, color: "#374151" }}>
          Есть балкон / лоджия
        </span>
      </label>

      {/* Validation error (shown after first submit attempt) */}
      {touched && validationError && (
        <div style={errorBoxStyle}>{validationError}</div>
      )}

      {/* API error */}
      {error && <div style={errorBoxStyle}>{error}</div>}

      <button type="submit" disabled={!canSubmit} style={primaryBtn(canSubmit)}>
        {isPending ? (
          <span
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              justifyContent: "center",
            }}
          >
            <svg
              width="15"
              height="15"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              style={{ animation: "ti-spin 1s linear infinite" }}
              aria-hidden="true"
            >
              <path d="M21 12a9 9 0 1 1-6.219-8.56" />
            </svg>
            Считаем…
          </span>
        ) : (
          "Оценить"
        )}
      </button>
      <style>{`@keyframes ti-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
    </form>
  );
}

function Required() {
  return <span style={{ color: "#ef4444", marginLeft: 2 }}>*</span>;
}

const labelStyle: React.CSSProperties = {
  display: "block",
  fontSize: 12,
  color: "#5b6066",
  marginBottom: 4,
  textTransform: "uppercase",
  letterSpacing: 0.4,
  fontWeight: 600,
};

const inputStyle: React.CSSProperties = {
  padding: "8px 10px",
  border: "1px solid #d1d5db",
  borderRadius: 6,
  fontSize: 14,
  width: "100%",
  boxSizing: "border-box",
  color: "#1a1d23",
  background: "#fff",
};

const errorBoxStyle: React.CSSProperties = {
  padding: "10px 12px",
  background: "#fef2f2",
  border: "1px solid #fecaca",
  borderRadius: 6,
  color: "#991b1b",
  fontSize: 13,
};

const primaryBtn = (enabled: boolean): React.CSSProperties => ({
  padding: "11px 18px",
  background: enabled ? "#1d4ed8" : "#9ca3af",
  color: "#fff",
  border: "none",
  borderRadius: 8,
  fontSize: 15,
  fontWeight: 600,
  cursor: enabled ? "pointer" : "not-allowed",
  marginTop: 4,
  transition: "background 0.15s",
});
