"use client";

import { useEffect, useState } from "react";
import { Field, Input } from "@/components/ui/Field";
import { apiGet } from "@/lib/api";
import type { BuildingSummary } from "@/lib/buildings";

export function BuildingPicker({
  value,
  selected,
  error,
  onSelect,
  onClearError,
}: {
  value: number | null;
  selected: BuildingSummary | null;
  error?: string;
  onSelect: (building: BuildingSummary | null) => void;
  onClearError?: () => void;
}) {
  const [query, setQuery] = useState("");
  const [options, setOptions] = useState<BuildingSummary[]>([]);

  useEffect(() => {
    if (selected) setQuery(`${selected.name} (${selected.code})`);
  }, [selected]);

  const search = async (q: string) => {
    setQuery(q);
    if (value) onSelect(null);
    onClearError?.();
    if (q.length < 1) {
      setOptions([]);
      return;
    }
    try {
      const params = new URLSearchParams({ q, is_active: "1", per_page: "20" });
      const result = await apiGet<{ data: BuildingSummary[] }>(`/buildings?${params}`);
      setOptions(result.data ?? []);
    } catch {
      setOptions([]);
    }
  };

  return (
    <Field
      label="ساختمان مرکزی شعبه *"
      error={error}
      hint="فقط یک ساختمان به‌عنوان ساختمان مرکزی این شعبه انتخاب می‌شود. سایر ساختمان‌ها بعداً قابل اختصاص هستند."
    >
      <Input
        value={query}
        invalid={Boolean(error)}
        placeholder="جستجوی نام یا کد ساختمان"
        onChange={(e) => search(e.target.value)}
      />
      {options.length > 0 ? (
        <ul className="mt-1 max-h-40 overflow-y-auto rounded-xl border border-[var(--border)] bg-white text-sm shadow-sm">
          {options.map((building) => (
            <li key={building.id}>
              <button
                type="button"
                className="block w-full px-3 py-2 text-right hover:bg-slate-50"
                onClick={() => {
                  setQuery(`${building.name} (${building.code})`);
                  setOptions([]);
                  onSelect(building);
                }}
              >
                <span className="font-medium">{building.name}</span>
                <span className="mr-2 font-mono text-xs text-[var(--muted)]">{building.code}</span>
                {building.city ? (
                  <span className="mr-2 text-xs text-[var(--muted)]">{building.city}</span>
                ) : null}
              </button>
            </li>
          ))}
        </ul>
      ) : null}
    </Field>
  );
}
