"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Field, Input, Select } from "@/components/ui/Field";
import {
  IRAN_PROVINCES,
  citiesForProvinceName,
  filterCities,
} from "@/lib/iran-geo";

export function ProvinceCityFields({
  province,
  city,
  onProvinceChange,
  onCityChange,
  required = false,
  provinceError,
  cityError,
}: {
  province: string;
  city: string;
  onProvinceChange: (province: string) => void;
  onCityChange: (city: string) => void;
  required?: boolean;
  provinceError?: string;
  cityError?: string;
}) {
  const cities = useMemo(() => citiesForProvinceName(province), [province]);
  const [query, setQuery] = useState(city);
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setQuery(city);
  }, [city]);

  useEffect(() => {
    const onDocClick = (e: MouseEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, []);

  const filtered = useMemo(() => filterCities(cities, query), [cities, query]);

  return (
    <>
      <Field label={required ? "استان *" : "استان"} error={provinceError}>
        <Select
          value={province}
          invalid={Boolean(provinceError)}
          onChange={(e) => {
            const next = e.target.value;
            onProvinceChange(next);
            setQuery("");
            setOpen(false);
          }}
        >
          <option value="">لطفا انتخاب کنید</option>
          {IRAN_PROVINCES.map((p) => (
            <option key={p.id} value={p.name}>
              {p.name}
            </option>
          ))}
        </Select>
      </Field>

      <Field label={required ? "شهر *" : "شهر"} error={cityError}>
        <div ref={rootRef} className={`relative ${open ? "z-[1001]" : ""}`}>
          <Input
            value={query}
            invalid={Boolean(cityError)}
            placeholder={province ? "جستجو یا انتخاب شهر" : "ابتدا استان را انتخاب کنید"}
            disabled={!province}
            onFocus={() => {
              if (province) setOpen(true);
            }}
            onChange={(e) => {
              const next = e.target.value;
              setQuery(next);
              setOpen(true);
              if (city && next !== city) onCityChange("");
            }}
            autoComplete="off"
          />
          {open && province ? (
            <ul className="absolute z-10 mt-1 max-h-48 w-full overflow-y-auto rounded-xl border border-[var(--border)] bg-white text-sm shadow-sm">
              {filtered.length === 0 ? (
                <li className="px-3 py-2 text-[var(--muted)]">شهری یافت نشد</li>
              ) : (
                filtered.map((c) => (
                  <li key={c.id}>
                    <button
                      type="button"
                      className="block w-full px-3 py-2 text-right hover:bg-slate-50"
                      onClick={() => {
                        onCityChange(c.name);
                        setQuery(c.name);
                        setOpen(false);
                      }}
                    >
                      {c.name}
                    </button>
                  </li>
                ))
              )}
            </ul>
          ) : null}
        </div>
      </Field>
    </>
  );
}
