'use client';
import { PLANS, onSale, tl } from '@/lib/plans';
import { useEffect, useState } from 'react';
import { idariList, parcelLookup, type ParcelResult, type Opt } from '@/lib/tkgmClient';

export type Pick = { il: string; ilce: string; mahalle: string };
/**
 * Harita masasının alt çubuğu: il / ilçe / mahalle (paketli listeler) + ada / parsel → TKGM sorgusu.
 * Bulunan parsel onFound ile haritaya verilir; ardından düğme "videoyu hazırla" bağlantısına dönüşür.
 */
export function ParcelBar({ initial, onFound, cta }: { initial?: Pick & { ada: string; parsel: string }; onFound: (p: ParcelResult, pick: Pick) => void; cta: (p: ParcelResult, pick: Pick) => string }) {
  const [il, setIl] = useState<Opt[]>([]); const [ilce, setIlce] = useState<Opt[]>([]); const [mah, setMah] = useState<Opt[]>([]);
  const [f, setF] = useState({ il: initial?.il || '', ilce: initial?.ilce || '', mahalle: initial?.mahalle || '', ada: initial?.ada || '', parsel: initial?.parsel || '' });
  const [found, setFound] = useState<ParcelResult | null>(null);
  const [busy, setBusy] = useState(false); const [msg, setMsg] = useState('');
  useEffect(() => { idariList('il').then(setIl).catch(() => {}); }, []);
  useEffect(() => { setIlce([]); if (f.il) idariList('ilce', f.il).then(setIlce).catch(() => {}); }, [f.il]);
  useEffect(() => { setMah([]); if (f.ilce) idariList('mahalle', f.ilce).then(setMah).catch(() => {}); }, [f.ilce]);
  const set = (k: keyof typeof f, v: string) => { setFound(null); setMsg(''); setF((o) => ({ ...o, [k]: v, ...(k === 'il' ? { ilce: '', mahalle: '' } : k === 'ilce' ? { mahalle: '' } : {}) })); };
  const pick = { il: f.il, ilce: f.ilce, mahalle: f.mahalle };
  async function go() {
    setBusy(true); setMsg('');
    for (let i = 0; i < 3; i++) {
      try { const p = await parcelLookup(f.mahalle, f.ada, f.parsel); setFound(p); onFound(p, pick); break; }
      catch (e) {
        if ((e as { notFound?: boolean }).notFound) { setMsg('Bu ada/parsel Tapu Kadastro kayıtlarında yok. Numaraları kontrol edin.'); break; }
        if (i === 2) { setMsg('Tapu Kadastro servisi şu an yanıt vermiyor. Birkaç dakika sonra yeniden deneyin.'); break; }
        setMsg('Tapu Kadastro servisi yoğun, yeniden deneniyor…'); await new Promise((r) => setTimeout(r, 3000 * (i + 1)));
      }
    }
    setBusy(false);
  }
  const ready = f.mahalle && f.ada && f.parsel;
  const S = ({ k, label, opts, dis }: { k: 'il' | 'ilce' | 'mahalle'; label: string; opts: Opt[]; dis?: boolean }) => (
    <label key={k} className={`cell border-b border-r md:border-b-0 ${k === 'mahalle' ? 'col-span-2 md:col-span-1' : ''}`}><span className="tag">{label}</span>
      <select aria-label={label} value={f[k]} disabled={dis || !opts.length} onChange={(e) => set(k, e.target.value)}><option value="">Seçin</option>{opts.map((o) => <option key={o.id} value={o.id}>{o.text}</option>)}</select></label>
  );
  return (
    <div>
      <form onSubmit={(e) => { e.preventDefault(); if (found) location.href = cta(found, pick); else if (ready) go(); }} className="cells grid-cols-2 md:grid-cols-[1.1fr_1.1fr_1.3fr_.6fr_.6fr_250px]">
        {S({ k: 'il', label: 'İl', opts: il })}{S({ k: 'ilce', label: 'İlçe', opts: ilce, dis: !f.il })}{S({ k: 'mahalle', label: 'Mahalle / köy', opts: mah, dis: !f.ilce })}
        <label className="cell border-b border-r md:border-b-0"><span className="tag">Ada</span><input aria-label="Ada" inputMode="numeric" placeholder="101" value={f.ada} onChange={(e) => set('ada', e.target.value.replace(/\D/g, ''))} className="num" /></label>
        <label className="cell border-b md:border-b-0 md:border-r"><span className="tag">Parsel</span><input aria-label="Parsel" inputMode="numeric" placeholder="5" value={f.parsel} onChange={(e) => set('parsel', e.target.value.replace(/\D/g, ''))} className="num" /></label>
        <button disabled={busy || (!found && !ready)} className="col-span-2 flex min-h-[64px] flex-col items-start justify-center bg-signal px-4 text-left text-ink hover:bg-signal-dark disabled:bg-signal/50 md:col-span-1">
          <span className="text-[17px] font-extrabold">{busy ? 'TKGM sorgulanıyor…' : found ? 'Bu parselin videosunu hazırla' : 'Parseli haritada bul'}</span>
          <span className="text-[12.5px] font-medium">{found ? <>{onSale(PLANS[0]) && <s className="mr-1 opacity-60">{tl(PLANS[0].listPrice!)}</s>}{tl(PLANS[0].price)}{onSale(PLANS[0]) ? ' lansman fiyatı' : ''} · ödeme sonrası yaklaşık 10 dk</> : 'Sınır Tapu Kadastro kaydından çizilir'}</span>
        </button>
      </form>
      {msg && <div role="status" className="bg-ink px-4 py-2 text-[13.5px] text-white">{msg}</div>}
    </div>
  );
}
