'use client';
import { useEffect, useMemo, useRef, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Icon } from '@/lib/icons';
import { CATS, CITIES, AMEN_MAP } from '@/lib/data';
import { useGo } from '@/lib/router';
import { saveBusiness } from '@/lib/actions';

export type BusinessInitial = {
  id: number;
  name: string;
  cat: string;
  city: string;
  area: string;
  address: string;
  phone: string;
  descr: string;
  price: string;
  unit: string;
  status: string;
  amenities: string[];
  photos: string[];
};

const MAX_PHOTOS = 8;
const AMENITY_KEYS = Object.keys(AMEN_MAP);

export function BusinessEditor({ business }: { business?: BusinessInitial | null }) {
  const { go } = useGo();
  const router = useRouter();
  const b = business || null;

  const [name, setName] = useState(b?.name || '');
  const [cat, setCat] = useState(b?.cat || 'restaurants');
  const [city, setCity] = useState(b?.city || 'Alger');
  const [area, setArea] = useState(b?.area || '');
  const [address, setAddress] = useState(b?.address || '');
  const [phone, setPhone] = useState(b?.phone || '');
  const [price, setPrice] = useState(b?.price || '');
  const [unit, setUnit] = useState(b?.unit || '/ pers.');
  const [descr, setDescr] = useState(b?.descr || '');
  const [status, setStatus] = useState(b?.status === 'soon' ? 'soon' : 'open');
  const [amenities, setAmenities] = useState<Set<string>>(new Set(b?.amenities || ['resa', 'card']));
  const [existing, setExisting] = useState<string[]>(b?.photos || []);
  const [files, setFiles] = useState<File[]>([]);
  const [msg, setMsg] = useState<{ ok?: boolean; error?: string }>({});
  const [pending, startTransition] = useTransition();
  const fileRef = useRef<HTMLInputElement>(null);

  const previews = useMemo(() => files.map((f) => URL.createObjectURL(f)), [files]);
  useEffect(() => () => previews.forEach((u) => URL.revokeObjectURL(u)), [previews]);
  const total = existing.length + files.length;
  const cover = previews[0] || existing[0] || null;

  const toggleAmen = (k: string) =>
    setAmenities((s) => {
      const n = new Set(s);
      n.has(k) ? n.delete(k) : n.add(k);
      return n;
    });

  const onPick = (e: React.ChangeEvent<HTMLInputElement>) => {
    const picked = Array.from(e.target.files || []);
    const room = MAX_PHOTOS - total;
    if (room > 0) setFiles((f) => [...f, ...picked.slice(0, room)]);
    e.target.value = '';
  };

  const submit = () => {
    if (!name.trim()) {
      setMsg({ error: 'Le nom du commerce est obligatoire.' });
      return;
    }
    setMsg({});
    const fd = new FormData();
    fd.set('name', name);
    fd.set('cat', cat);
    fd.set('city', city);
    fd.set('area', area);
    fd.set('address', address);
    fd.set('phone', phone);
    fd.set('price', price);
    fd.set('unit', unit);
    fd.set('status', status);
    fd.set('descr', descr);
    [...amenities].forEach((a) => fd.append('amenities', a));
    fd.set('keepPhotos', JSON.stringify(existing));
    files.forEach((f) => fd.append('photos', f));
    startTransition(async () => {
      const r = await saveBusiness(fd);
      if (r.ok) {
        setFiles([]);
        setMsg({ ok: true });
        router.refresh();
      } else setMsg({ error: r.error || 'Erreur' });
    });
  };

  return (
    <div className="grid" style={{ gridTemplateColumns: '1fr 360px', gap: 16, alignItems: 'start' }}>
      <div className="panel">
        <div className="between" style={{ marginBottom: 16 }}>
          <h3 className="h4">Informations du commerce</h3>
          {b && (
            <button className="btn btn-ghost btn-sm" onClick={() => go('detail', { id: b.id })}>
              <Icon name="arrowUpRight" size={15} />Voir la fiche publique
            </button>
          )}
        </div>

        <div className="field" style={{ marginBottom: 14 }}>
          <span className="label">Nom du commerce</span>
          <div className="input"><Icon name="store" size={16} /><input value={name} onChange={(e) => setName(e.target.value)} placeholder="Ex. Dar Yasmine" /></div>
        </div>

        <div className="grid cols-2" style={{ gap: 12 }}>
          <div className="field">
            <span className="label">Catégorie</span>
            <div className="input">
              <select value={cat} onChange={(e) => setCat(e.target.value)} style={{ border: 'none', outline: 'none', background: 'none', width: '100%' }}>
                {CATS.map((c) => <option key={c.key} value={c.key}>{c.name}</option>)}
              </select>
            </div>
          </div>
          <div className="field">
            <span className="label">Statut</span>
            <div className="seg" style={{ width: '100%' }}>
              <button type="button" className={status === 'open' ? 'on' : ''} style={{ flex: 1, justifyContent: 'center' }} onClick={() => setStatus('open')}>Ouvert</button>
              <button type="button" className={status === 'soon' ? 'on' : ''} style={{ flex: 1, justifyContent: 'center' }} onClick={() => setStatus('soon')}>Sur RDV</button>
            </div>
          </div>
        </div>

        <div className="grid cols-2" style={{ gap: 12, marginTop: 14 }}>
          <div className="field">
            <span className="label">Ville</span>
            <div className="input"><Icon name="pin" size={16} /><select value={city} onChange={(e) => setCity(e.target.value)} style={{ border: 'none', outline: 'none', background: 'none', width: '100%' }}>{CITIES.map((c) => <option key={c}>{c}</option>)}</select></div>
          </div>
          <div className="field">
            <span className="label">Quartier</span>
            <div className="input"><input value={area} onChange={(e) => setArea(e.target.value)} placeholder="Ex. Hydra" /></div>
          </div>
        </div>

        <div className="field" style={{ marginTop: 14 }}>
          <span className="label">Adresse</span>
          <div className="input"><Icon name="pin" size={16} /><input value={address} onChange={(e) => setAddress(e.target.value)} placeholder="14 chemin Gaddouche, Hydra, Alger" /></div>
        </div>

        <div className="grid cols-2" style={{ gap: 12, marginTop: 14 }}>
          <div className="field">
            <span className="label">Téléphone</span>
            <div className="input"><Icon name="phone" size={16} /><input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+213 6 .. .. .. .." /></div>
          </div>
          <div className="field">
            <span className="label">Prix indicatif</span>
            <div className="input">
              <Icon name="banknote" size={16} />
              <input value={price} onChange={(e) => setPrice(e.target.value)} placeholder="2 000" style={{ width: '50%' }} />
              <input value={unit} onChange={(e) => setUnit(e.target.value)} placeholder="/ pers." style={{ width: '50%', color: 'var(--muted)' }} />
            </div>
          </div>
        </div>

        <div className="field" style={{ marginTop: 14 }}>
          <span className="label">Description</span>
          <div className="input" style={{ alignItems: 'flex-start' }}>
            <textarea value={descr} onChange={(e) => setDescr(e.target.value)} rows={4} placeholder="Présentez votre établissement, vos spécialités, votre ambiance…" style={{ border: 'none', outline: 'none', background: 'none', width: '100%', resize: 'vertical', fontSize: 14 }} />
          </div>
        </div>

        <div className="label" style={{ margin: '18px 0 10px' }}>Équipements & services</div>
        <div className="row wrapf gap8">
          {AMENITY_KEYS.map((k) => (
            <div key={k} className={'chip ' + (amenities.has(k) ? 'active' : '')} onClick={() => toggleAmen(k)}>
              <Icon name={AMEN_MAP[k].icon} size={15} stroke={1.8} />{AMEN_MAP[k].label}
            </div>
          ))}
        </div>

        {msg.error && (
          <div className="row gap8" style={{ marginTop: 16, padding: '11px 14px', background: 'var(--red-tint)', color: 'var(--red-dark)', borderRadius: 'var(--r-md)', fontSize: 13.5, fontWeight: 600 }}>
            <Icon name="info" size={16} />{msg.error}
          </div>
        )}
        <div className="row gap12" style={{ marginTop: 18, alignItems: 'center' }}>
          <button className="btn btn-red" disabled={pending} onClick={submit} style={pending ? { opacity: 0.7 } : undefined}>
            <Icon name="check" size={16} stroke={2.5} />{pending ? 'Enregistrement…' : b ? 'Enregistrer' : 'Créer ma fiche'}
          </button>
          {msg.ok && <span className="small row gap8" style={{ color: 'var(--teal)', fontWeight: 600 }}><Icon name="checkCircle" size={16} />Fiche enregistrée et publiée</span>}
        </div>
      </div>

      <div className="panel">
        <h3 className="h4" style={{ marginBottom: 12 }}>Photos</h3>
        <input ref={fileRef} type="file" accept="image/*" multiple onChange={onPick} style={{ display: 'none' }} />
        <div className="ph" style={{ height: 150, borderRadius: 12, padding: 0, overflow: 'hidden' }}>
          {cover ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={cover} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          ) : (
            <Icon name={CATS.find((c) => c.key === cat)?.icon || 'store'} size={48} stroke={1.4} style={{ color: 'var(--faint)' }} />
          )}
        </div>
        <div className="grid cols-3" style={{ gap: 8, marginTop: 10 }}>
          {existing.map((src) => (
            <div key={src} style={{ position: 'relative', borderRadius: 10, overflow: 'hidden', aspectRatio: '1' }}>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              <button className="iconbtn danger" style={{ position: 'absolute', right: 4, top: 4, width: 24, height: 24, background: 'rgba(255,255,255,0.92)' }} onClick={() => setExisting((s) => s.filter((x) => x !== src))}><Icon name="x" size={13} /></button>
            </div>
          ))}
          {previews.map((src, i) => (
            <div key={src} style={{ position: 'relative', borderRadius: 10, overflow: 'hidden', aspectRatio: '1' }}>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              <button className="iconbtn danger" style={{ position: 'absolute', right: 4, top: 4, width: 24, height: 24, background: 'rgba(255,255,255,0.92)' }} onClick={() => setFiles((f) => f.filter((_, idx) => idx !== i))}><Icon name="x" size={13} /></button>
            </div>
          ))}
        </div>
        {total < MAX_PHOTOS && (
          <button className="btn btn-ghost btn-block" style={{ marginTop: 12, borderStyle: 'dashed' }} onClick={() => fileRef.current?.click()}>
            <Icon name="camera" size={16} />Ajouter des photos
          </button>
        )}
        <div className="tiny" style={{ marginTop: 8 }}>JPG, PNG, WebP — 6 Mo max. La 1ʳᵉ photo est la principale.</div>
      </div>
    </div>
  );
}
