'use client';
import { useState, useTransition } from 'react';
import { Icon } from '@/lib/icons';
import { AdImage } from '@/components/AdImage';
import { AdCard, CondChip } from '@/components/AdCard';
import { Crumb } from '@/components/Crumb';
import { adCat, type Ad } from '@/lib/data';
import { useGo } from '@/lib/router';
import { useAuth } from '@/components/AuthProvider';
import { startConversation } from '@/lib/actions';

export function AnnonceDetailClient({ d, similar }: { d: Ad; similar: Ad[] }) {
  const { go } = useGo();
  const { user, isFav, toggleFav } = useAuth();
  const saved = isFav('ad', d.id);
  const [thumb, setThumb] = useState(0);
  const [showNum, setShowNum] = useState(false);
  const [contacting, startContact] = useTransition();
  const [msgError, setMsgError] = useState('');
  const s = d.seller;
  const cat = adCat(d.cat);

  const contactSeller = () => {
    if (!user) {
      go('auth', { mode: 'login' });
      return;
    }
    setMsgError('');
    startContact(async () => {
      const r = await startConversation(d.id);
      if (r.ok && r.convId) go('compte', { tab: 'messages', conv: r.convId });
      else if (r.error === 'own') setMsgError('C’est votre propre annonce.');
      else setMsgError('Impossible d’ouvrir la conversation.');
    });
  };

  return (
    <div className="wrap" style={{ paddingTop: 20, paddingBottom: 40 }}>
      <Crumb
        items={[
          { label: 'Accueil', go: ['home'] },
          { label: 'Annonces', go: ['annonces'] },
          { label: cat?.name ?? '', go: ['annonces', { cat: d.cat }] },
          { label: d.title },
        ]}
      />
      <div className="detail-layout" style={{ marginTop: 16 }}>
        <div>
          <AdImage photos={d.photos} cat={d.cat} icon={d.icon} h={380} idx={thumb} radius={18} />
          <div className="row gap8" style={{ marginTop: 10 }}>
            {Array.from({ length: d.photos && d.photos.length ? d.photos.length : 4 }).map((_, i) => (
              <div
                key={i}
                onClick={() => setThumb(i)}
                style={{
                  flex: 1,
                  cursor: 'pointer',
                  borderRadius: 12,
                  overflow: 'hidden',
                  border: thumb === i ? '2px solid var(--red)' : '2px solid transparent',
                }}
              >
                <AdImage photos={d.photos} cat={d.cat} icon={d.icon} h={72} idx={d.photos && d.photos.length ? i : i + 1} radius={10} />
              </div>
            ))}
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '24px 0' }}></div>
          <h3 className="h3">Description</h3>
          <p className="lead" style={{ marginTop: 10 }}>{d.desc}</p>
          <div className="grid cols-2" style={{ marginTop: 18, gap: 12 }}>
            {(
              [
                ['tag', 'Catégorie', cat?.name ?? '—'],
                ['refresh', 'État', d.cond || '—'],
                ['pin', 'Localisation', d.area + ', ' + d.city],
                ['clock', 'Publiée', d.when],
              ] as const
            ).map((r, i) => (
              <div key={i} className="amenity">
                <div className="ai"><Icon name={r[0]} size={18} stroke={1.8} /></div>
                <div>
                  <div className="tiny">{r[1]}</div>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{r[2]}</div>
                </div>
              </div>
            ))}
          </div>

          <div className="panel" style={{ marginTop: 22, background: 'var(--teal-tint)', border: 'none', display: 'flex', gap: 12 }}>
            <Icon name="shield" size={22} stroke={1.8} style={{ color: 'var(--teal)', flexShrink: 0 }} />
            <div>
              <div className="h4" style={{ color: 'var(--teal)' }}>Conseils de sécurité</div>
              <p className="small" style={{ marginTop: 6, color: 'var(--sub)' }}>
                Privilégiez une rencontre dans un lieu public, vérifiez le produit avant de payer et n’envoyez jamais d’argent à l’avance.
              </p>
            </div>
          </div>

          <h3 className="h3" style={{ marginTop: 28 }}>Annonces similaires</h3>
          <div className="grid cols-3" style={{ marginTop: 14 }}>
            {similar.map((a, i) => <AdCard key={a.id} d={a} idx={i} />)}
          </div>
        </div>

        <div>
          <div className="booking-box">
            <CondChip c={d.cond} />
            <h1 className="h1" style={{ fontSize: 32, marginTop: d.cond ? 10 : 0 }}>{d.price} DA{d.unit || ''}</h1>
            {d.nego && <div className="small" style={{ marginTop: 4 }}>Prix négociable</div>}
            <div className="h4" style={{ marginTop: 12, fontFamily: 'var(--body)', fontWeight: 600 }}>{d.title}</div>
            <div className="lcard-meta" style={{ marginTop: 8 }}>
              <Icon name="pin" size={14} stroke={1.8} />
              <span>{d.area}, {d.city} · {d.when}</span>
            </div>
            <button
              className="btn btn-red btn-block btn-lg"
              style={{ marginTop: 18, ...(contacting ? { opacity: 0.7 } : {}) }}
              disabled={contacting}
              onClick={contactSeller}
            >
              <Icon name="message" size={18} stroke={1.9} />
              {!user ? 'Se connecter pour écrire' : contacting ? 'Ouverture…' : 'Envoyer un message'}
            </button>
            {msgError && <div className="tiny" style={{ color: 'var(--red-dark)', marginTop: 8, fontWeight: 600 }}>{msgError}</div>}
            <button className="btn btn-ghost btn-block" style={{ marginTop: 10 }} onClick={() => setShowNum(true)}>
              <Icon name="phone" size={16} />{showNum ? '+213 6 12 34 56 78' : 'Afficher le numéro'}
            </button>
          </div>

          <div className="panel" style={{ marginTop: 14 }}>
            <div className="row gap12">
              <div className="avatar" style={{ background: s.t === 'pro' ? 'var(--ink)' : 'var(--red)', width: 46, height: 46 }}>{s.n[0]}</div>
              <div style={{ flex: 1 }}>
                <div className="row gap8">
                  <span style={{ fontWeight: 700, fontSize: 15 }}>{s.n}</span>
                  {s.t === 'pro' && (
                    <span
                      className="chip chip-sm"
                      style={{ background: 'var(--red-tint)', color: 'var(--red-dark)', border: 'none', padding: '2px 8px' }}
                    >
                      Pro
                    </span>
                  )}
                </div>
                <div className="row gap8" style={{ marginTop: 3 }}>
                  <Icon name="star" size={13} fill="var(--gold)" style={{ color: 'var(--gold)' }} />
                  <span className="small">{s.r} · membre depuis {s.since}</span>
                </div>
              </div>
            </div>
            <div className="between" style={{ marginTop: 14 }}>
              <span className="small">{s.ads} annonces publiées</span>
              <a
                className="small"
                style={{ fontWeight: 600, color: 'var(--red-dark)', cursor: 'pointer' }}
                onClick={() => go('vendeur', { id: d.id })}
              >
                Voir le profil
              </a>
            </div>
          </div>
          <div className="row gap8" style={{ marginTop: 14, justifyContent: 'center' }}>
            <button className={'btn btn-sm ' + (saved ? 'btn-red' : 'btn-ghost')} onClick={() => toggleFav('ad', d.id)}>
              <Icon name="heart" size={15} fill={saved ? '#fff' : 'none'} />{saved ? 'Sauvegardé' : 'Sauvegarder'}
            </button>
            <button
              className="btn btn-ghost btn-sm"
              onClick={() => {
                const url = typeof window !== 'undefined' ? window.location.href : '';
                if (navigator.share) navigator.share({ title: d.title, url }).catch(() => {});
                else navigator.clipboard?.writeText(url);
              }}
            >
              <Icon name="share" size={15} />Partager
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => go('aide')}><Icon name="info" size={15} />Signaler</button>
          </div>
        </div>
      </div>
    </div>
  );
}
