'use client';
import { useEffect, useMemo, useRef, useState, useTransition } from 'react';
import { Icon } from '@/lib/icons';
import { AD_CATS, CITIES } from '@/lib/data';
import { CondChip } from '@/components/AdCard';
import { useGo } from '@/lib/router';
import { useAuth } from '@/components/AuthProvider';
import { createAd, updateAd } from '@/lib/actions';

export type AdEditInitial = {
  id: number;
  title: string;
  cat: string;
  price: string;
  city: string;
  cond: string;
  nego: boolean;
  phone: string;
  descr: string;
  photos: string[];
};

const MAX_PHOTOS = 8;
const CONDS = ['Neuf', 'Comme neuf', 'Très bon état', 'Bon état'];

export function PostAdForm({ initial }: { initial?: AdEditInitial }) {
  const { go } = useGo();
  const { user } = useAuth();
  const editing = !!initial;

  const [cat, setCat] = useState(initial?.cat || 'tel');
  const [cond, setCond] = useState(initial?.cond || 'Très bon état');
  const [nego, setNego] = useState(initial?.nego ?? true);
  const [title, setTitle] = useState(initial?.title || '');
  const [price, setPrice] = useState(initial?.price || '');
  const [city, setCity] = useState(initial?.city || 'Alger');
  const [descr, setDescr] = useState(initial?.descr || '');
  const [phone, setPhone] = useState(initial?.phone || '');
  const [existing, setExisting] = useState<string[]>(initial?.photos || []);
  const [files, setFiles] = useState<File[]>([]);
  const [error, setError] = useState('');
  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 coverSrc = previews[0] || existing[0] || null;

  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 (!user) {
      go('auth', { mode: 'login' });
      return;
    }
    if (!title.trim()) {
      setError('Le titre de l’annonce est obligatoire.');
      return;
    }
    setError('');
    const fd = new FormData();
    fd.set('title', title);
    fd.set('cat', cat);
    fd.set('price', price);
    fd.set('city', city);
    fd.set('cond', cond);
    fd.set('nego', nego ? '1' : '0');
    fd.set('phone', phone);
    fd.set('descr', descr);
    files.forEach((f) => fd.append('photos', f));
    if (editing) {
      fd.set('id', String(initial!.id));
      fd.set('keepPhotos', JSON.stringify(existing));
    }
    startTransition(async () => {
      const r = editing ? await updateAd(fd) : await createAd(fd);
      if (r.ok && r.id) go('annonce', { id: r.id });
      else if (r.error && r.error !== 'auth') setError(r.error);
    });
  };

  return (
    <div className="wrap" style={{ paddingTop: 24, paddingBottom: 50 }}>
      <button
        className="row gap8"
        style={{ fontWeight: 600, fontSize: 14, color: 'var(--sub)' }}
        onClick={() => go(editing ? 'compte' : 'annonces', editing ? { tab: 'annonces' } : {})}
      >
        <Icon name="arrowLeft" size={17} stroke={2} />{editing ? 'Retour à mes annonces' : 'Retour aux annonces'}
      </button>
      <h1 className="h1" style={{ fontSize: 34, marginTop: 14 }}>
        {editing ? 'Modifier l’annonce' : 'Déposer une annonce'}
      </h1>
      <p className="body" style={{ marginTop: 6 }}>
        {editing
          ? 'Mettez à jour les informations et les photos de votre annonce.'
          : 'C’est gratuit. Votre annonce sera visible par des milliers d’Algériens.'}
      </p>

      <div className="detail-layout" style={{ marginTop: 24 }}>
        <div className="panel" style={{ padding: 24 }}>
          <div className="field">
            <span className="label">Titre de l’annonce</span>
            <div className="input"><input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Ex. iPhone 13 Pro 256 Go" /></div>
          </div>

          <div className="label" style={{ margin: '20px 0 10px' }}>Catégorie</div>
          <div className="row wrapf gap8">
            {AD_CATS.map((c) => (
              <div key={c.key} className={'chip ' + (cat === c.key ? 'active' : '')} onClick={() => setCat(c.key)}>
                <Icon name={c.icon} size={15} stroke={1.8} />{c.name}
              </div>
            ))}
          </div>

          <div className="label" style={{ margin: '20px 0 10px' }}>État</div>
          <div className="row wrapf gap8">
            {CONDS.map((c) => (
              <div key={c} className={'chip ' + (cond === c ? 'active' : '')} onClick={() => setCond(c)}>{c}</div>
            ))}
          </div>

          <div className="grid cols-2" style={{ gap: 14, marginTop: 20 }}>
            <div className="field">
              <span className="label">Prix</span>
              <div className="input">
                <Icon name="banknote" size={17} />
                <input value={price} onChange={(e) => setPrice(e.target.value)} placeholder="0" />
                <span className="small" style={{ fontWeight: 600 }}>DA</span>
              </div>
            </div>
            <div className="field">
              <span className="label">Localisation</span>
              <div className="input">
                <Icon name="pin" size={17} />
                <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>
          <label className="row gap8 small" style={{ cursor: 'pointer', marginTop: 12 }}>
            <input type="checkbox" checked={nego} onChange={(e) => setNego(e.target.checked)} />Prix négociable
          </label>

          <div className="label" style={{ margin: '20px 0 10px' }}>Photos</div>
          <input ref={fileRef} type="file" accept="image/*" multiple onChange={onPick} style={{ display: 'none' }} />
          <div className="grid cols-3" style={{ gap: 10 }}>
            {total < MAX_PHOTOS && (
              <div className="upload" onClick={() => fileRef.current?.click()}>
                <Icon name="plus" size={22} stroke={2} />
                <span className="tiny" style={{ marginTop: 4 }}>Ajouter</span>
              </div>
            )}
            {existing.map((src) => (
              <div key={src} style={{ position: 'relative', borderRadius: 12, 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: 6, top: 6, width: 28, height: 28, background: 'rgba(255,255,255,0.92)' }}
                  onClick={() => setExisting((s) => s.filter((x) => x !== src))}
                  title="Retirer"
                >
                  <Icon name="x" size={15} />
                </button>
              </div>
            ))}
            {previews.map((src, i) => (
              <div key={src} style={{ position: 'relative', borderRadius: 12, 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: 6, top: 6, width: 28, height: 28, background: 'rgba(255,255,255,0.92)' }}
                  onClick={() => setFiles((f) => f.filter((_, idx) => idx !== i))}
                  title="Retirer"
                >
                  <Icon name="x" size={15} />
                </button>
              </div>
            ))}
          </div>
          <div className="tiny" style={{ marginTop: 8 }}>
            Ajoutez jusqu’à {MAX_PHOTOS} photos (JPG, PNG, WebP — 6 Mo max). La première sera la photo principale.
          </div>

          <div className="field" style={{ marginTop: 20 }}>
            <span className="label">Description</span>
            <div className="input" style={{ alignItems: 'flex-start' }}>
              <textarea
                rows={5}
                value={descr}
                onChange={(e) => setDescr(e.target.value)}
                placeholder="Décrivez votre produit : caractéristiques, état, raison de la vente…"
                style={{ border: 'none', outline: 'none', background: 'none', resize: 'vertical', width: '100%', fontSize: 14.5 }}
              />
            </div>
          </div>
          <div className="field" style={{ marginTop: 14 }}>
            <span className="label">Téléphone</span>
            <div className="input">
              <Icon name="phone" size={17} />
              <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+213 6 .. .. .. .." />
            </div>
          </div>

          {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} />{error}
            </div>
          )}

          <button
            className="btn btn-red btn-block btn-lg"
            style={{ marginTop: 22, ...(pending ? { opacity: 0.7 } : {}) }}
            disabled={pending}
            onClick={submit}
          >
            <Icon name="check" size={18} stroke={2.5} />
            {!user
              ? 'Se connecter pour publier'
              : pending
              ? 'Enregistrement…'
              : editing
              ? 'Enregistrer les modifications'
              : 'Publier l’annonce'}
          </button>
        </div>

        <div>
          <div className="booking-box">
            <div className="tiny" style={{ fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--muted)', marginBottom: 12 }}>
              Aperçu
            </div>
            <div className="ph" style={{ height: 150, borderRadius: 14, padding: 0, overflow: 'hidden' }}>
              {coverSrc ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={coverSrc} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              ) : (
                <Icon name={AD_CATS.find((c) => c.key === cat)?.icon || 'tag'} size={48} stroke={1.4} style={{ color: 'var(--faint)' }} />
              )}
            </div>
            <div className="h4" style={{ marginTop: 12, minHeight: 22 }}>{title || 'Titre de votre annonce'}</div>
            <div className="h3" style={{ color: 'var(--red)', fontSize: 22, marginTop: 6 }}>
              {price || '0'} <span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600 }}>DA</span>
            </div>
            <div className="row gap8" style={{ marginTop: 10 }}>
              <CondChip c={cond} />
              {nego && <span className="tiny" style={{ alignSelf: 'center', fontWeight: 600 }}>Négociable</span>}
            </div>
          </div>
          <div className="panel" style={{ marginTop: 14, display: 'flex', gap: 12 }}>
            <Icon name="info" size={20} stroke={1.8} style={{ color: 'var(--muted)', flexShrink: 0 }} />
            <p className="small">
              Une annonce avec de bonnes photos et une description claire se vend{' '}
              <b style={{ color: 'var(--ink)' }}>3× plus vite</b>.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
