'use client';
import { useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Icon, Stars } from '@/lib/icons';
import { AdImage } from '@/components/AdImage';
import { Crumb } from '@/components/Crumb';
import type { Listing } from '@/lib/data';
import type { Review, ReviewStats } from '@/lib/queries';
import { useGo } from '@/lib/router';
import { addReview } from '@/lib/actions';

function ReviewForm({ businessId }: { businessId: number }) {
  const router = useRouter();
  const [rating, setRating] = useState(5);
  const [body, setBody] = useState('');
  const [error, setError] = useState('');
  const [pending, start] = useTransition();
  const submit = () => {
    const fd = new FormData();
    fd.set('businessId', String(businessId));
    fd.set('rating', String(rating));
    fd.set('body', body);
    setError('');
    start(async () => {
      const r = await addReview(fd);
      if (r.ok) { setBody(''); router.refresh(); }
      else setError(r.error || 'Erreur');
    });
  };
  return (
    <div className="panel" style={{ marginBottom: 16 }}>
      <div className="between" style={{ flexWrap: 'wrap', gap: 8 }}>
        <h4 className="h4">Laisser un avis</h4>
        <div className="row gap8">
          {[1, 2, 3, 4, 5].map((s) => (
            <Icon
              key={s}
              name="star"
              size={22}
              fill={s <= rating ? 'var(--gold)' : 'none'}
              style={{ color: s <= rating ? 'var(--gold)' : 'var(--line3)', cursor: 'pointer' }}
              onClick={() => setRating(s)}
            />
          ))}
        </div>
      </div>
      <div className="input" style={{ alignItems: 'flex-start', marginTop: 12 }}>
        <textarea
          value={body}
          onChange={(e) => setBody(e.target.value)}
          rows={3}
          placeholder="Partagez votre expérience…"
          style={{ border: 'none', outline: 'none', background: 'none', width: '100%', resize: 'vertical', fontSize: 14 }}
        />
      </div>
      {error && <div className="tiny" style={{ color: 'var(--red-dark)', marginTop: 8, fontWeight: 600 }}>{error}</div>}
      <button className="btn btn-red btn-sm" style={{ marginTop: 12 }} disabled={pending} onClick={submit}>
        <Icon name="check" size={15} stroke={2.4} />{pending ? 'Publication…' : 'Publier mon avis'}
      </button>
    </div>
  );
}

export function CommerceDetailClient({
  d,
  reviews,
  stats,
  canReview,
}: {
  d: Listing;
  reviews: Review[];
  stats: ReviewStats;
  canReview: boolean;
}) {
  const { go } = useGo();
  const [covers, setCovers] = useState(2);
  const [day, setDay] = useState(1);
  const days = ['Auj.', 'Dem.', 'Jeu', 'Ven', 'Sam'];
  const photos = d.photos || [];
  const ratingVal = stats.count ? stats.avg : d.rating;
  const reviewsCount = stats.count ? stats.count : d.reviews;
  return (
    <div className="wrap" style={{ paddingTop: 20, paddingBottom: 40 }}>
      <Crumb
        items={[
          { label: 'Accueil', go: ['home'] },
          { label: d.catName, go: ['category', { cat: d.cat }] },
          { label: d.name },
        ]}
      />

      <div className="detail-gallery" style={{ marginTop: 14 }}>
        <AdImage biz photos={photos} cat={d.cat} h="100%" idx={0} radius={18} style={{ gridRow: '1 / span 2' }} />
        <AdImage biz photos={photos} cat={d.cat} h="100%" idx={1} radius={18} />
        <AdImage biz photos={photos} cat={d.cat} h="100%" idx={2} radius={18} />
        <AdImage biz photos={photos} cat={d.cat} h="100%" idx={3} radius={18} />
        <div className="g4" style={{ position: 'relative' }}>
          <AdImage biz photos={photos} cat={d.cat} h="100%" idx={4} radius={18} />
          <div
            style={{
              position: 'absolute',
              inset: 0,
              background: 'rgba(26,23,20,0.55)',
              borderRadius: 18,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: '#fff',
              fontWeight: 700,
              cursor: 'pointer',
            }}
          >
            <span className="row gap8"><Icon name="camera" size={18} />+ 24 photos</span>
          </div>
        </div>
      </div>

      <div className="detail-layout">
        <div>
          <div className="between" style={{ alignItems: 'flex-start' }}>
            <div>
              <div className="row gap8" style={{ marginBottom: 8 }}>
                <span className="chip chip-sm" style={{ background: 'var(--red-tint)', color: 'var(--red-dark)', border: 'none' }}>{d.catName}</span>
                {d.verified && (
                  <span className="chip chip-sm" style={{ background: 'var(--teal-tint)', color: 'var(--teal)', border: 'none' }}>
                    <Icon name="verified" size={13} />Vérifié
                  </span>
                )}
              </div>
              <h1 className="h1" style={{ fontSize: 40 }}>{d.name}</h1>
              <div className="row gap16" style={{ marginTop: 10, flexWrap: 'wrap' }}>
                <span className="row gap8">
                  <Stars value={ratingVal} />
                  <b style={{ fontSize: 14 }}>{ratingVal.toFixed(1)}</b>
                  <span className="small">({reviewsCount} avis)</span>
                </span>
                <span className="small row gap8" style={{ alignItems: 'center' }}>
                  <Icon name="pin" size={15} stroke={1.8} />
                  <span>{d.area}, {d.city}</span>
                </span>
                <span className="small">{d.priceLevel}</span>
              </div>
            </div>
            <div className="row gap8 hide-m">
              <button className="btn btn-ghost btn-sm"><Icon name="share" size={16} /></button>
              <button className="btn btn-ghost btn-sm"><Icon name="heart" size={16} /></button>
            </div>
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '22px 0' }}></div>
          <h3 className="h3">À propos</h3>
          <p className="lead" style={{ marginTop: 10 }}>{d.desc}</p>
          <div className="row wrapf gap8" style={{ marginTop: 16 }}>
            {d.tags.map((t) => <span key={t} className="chip chip-sm">{t}</span>)}
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '24px 0' }}></div>
          <h3 className="h3">Équipements & services</h3>
          <div className="grid cols-2" style={{ marginTop: 14, gap: 14 }}>
            {d.amenities.map((a, i) => (
              <div className="amenity" key={i}>
                <div className="ai"><Icon name={a.icon} size={18} stroke={1.8} /></div>
                {a.label}
              </div>
            ))}
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '24px 0' }}></div>
          <h3 className="h3">Horaires</h3>
          <div className="panel" style={{ marginTop: 14, padding: 18 }}>
            {d.hours.map((h, i) => (
              <div key={i} className="between" style={{ padding: '8px 0', borderTop: i ? '1px solid var(--line2)' : 'none' }}>
                <span style={{ fontWeight: 600, fontSize: 14 }}>{h.d}</span>
                <span className="small" style={{ color: h.h === 'Fermé' ? 'var(--red)' : 'var(--sub)' }}>{h.h}</span>
              </div>
            ))}
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '24px 0' }}></div>
          <h3 className="h3">Localisation</h3>
          <div className="map-ph" style={{ height: 240, marginTop: 14 }}>
            <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-100%)' }}>
              <Icon name="pin" size={40} fill="var(--red)" style={{ color: 'var(--red)' }} stroke={1.5} />
            </div>
          </div>
          <div className="small row gap8" style={{ marginTop: 10 }}>
            <Icon name="pin" size={15} stroke={1.8} />{d.address}
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '24px 0' }}></div>
          <div className="between">
            <h3 className="h3">Avis ({reviewsCount})</h3>
            <span className="row gap8">
              <Icon name="star" size={18} fill="var(--gold)" style={{ color: 'var(--gold)' }} />
              <b>{ratingVal.toFixed(1)}</b>
              <span className="small">sur 5</span>
            </span>
          </div>
          {canReview && <div style={{ marginTop: 14 }}><ReviewForm businessId={d.id} /></div>}
          {reviews.length === 0 ? (
            <div className="panel" style={{ marginTop: 14, textAlign: 'center', padding: 32 }}>
              <Icon name="star" size={28} stroke={1.5} style={{ color: 'var(--faint)' }} />
              <p className="body" style={{ marginTop: 10 }}>Aucun avis pour le moment. Réservez et soyez le premier à donner votre avis&nbsp;!</p>
            </div>
          ) : (
            <div className="grid" style={{ marginTop: 14, gap: 12 }}>
              {reviews.map((rv) => (
                <div className="review" key={rv.id}>
                  <div className="between">
                    <div className="row gap12">
                      <div className="avatar" style={{ background: rv.color }}>{rv.author[0]?.toUpperCase()}</div>
                      <div>
                        <div style={{ fontWeight: 700, fontSize: 14 }}>{rv.author}{rv.mine && <span className="tiny" style={{ color: 'var(--muted)' }}> · vous</span>}</div>
                        <div className="tiny">{rv.when}</div>
                      </div>
                    </div>
                    <Stars value={rv.rating} size={13} />
                  </div>
                  {rv.body && <p className="body" style={{ marginTop: 12 }}>{rv.body}</p>}
                  {rv.reply && (
                    <div style={{ marginTop: 12, marginLeft: 16, padding: '12px 16px', background: 'var(--bg2)', borderRadius: 12, borderLeft: '3px solid var(--red)' }}>
                      <div className="row gap8" style={{ marginBottom: 4 }}>
                        <Icon name="store" size={14} stroke={1.8} style={{ color: 'var(--red)' }} />
                        <span style={{ fontWeight: 700, fontSize: 13 }}>Réponse de {d.name}</span>
                      </div>
                      <p className="small" style={{ color: 'var(--sub)' }}>{rv.reply}</p>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="booking-box">
          <div className="between" style={{ alignItems: 'flex-end' }}>
            <div>
              <span className="small">à partir de</span>
              <div className="h2" style={{ fontSize: 26 }}>{d.price} DA</div>
            </div>
            <span className="small">{d.unit}</span>
          </div>
          <div style={{ height: 1, background: 'var(--line)', margin: '16px 0' }}></div>
          <div className="label" style={{ marginBottom: 8 }}>Date</div>
          <div className="row gap8" style={{ overflowX: 'auto' }}>
            {days.map((dd, i) => (
              <div key={i} className={'daypick ' + (day === i ? 'on' : '')} onClick={() => setDay(i)}>
                <div style={{ fontWeight: 700, fontSize: 14, color: day === i ? 'var(--red-dark)' : 'var(--ink)' }}>{dd}</div>
                <div className="tiny">{12 + i} mai</div>
              </div>
            ))}
          </div>
          <div className="label" style={{ margin: '16px 0 8px' }}>Couverts</div>
          <div className="between">
            <span className="row gap8">
              <Icon name="users" size={18} stroke={1.8} style={{ color: 'var(--muted)' }} />
              <span>{covers} personne{covers > 1 ? 's' : ''}</span>
            </span>
            <div className="counter">
              <button onClick={() => setCovers(Math.max(1, covers - 1))}><Icon name="minus" size={16} /></button>
              <button onClick={() => setCovers(Math.min(12, covers + 1))}><Icon name="plus" size={16} /></button>
            </div>
          </div>
          <button
            className="btn btn-red btn-block btn-lg"
            style={{ marginTop: 18 }}
            onClick={() => go('booking', { id: d.id, covers, day })}
          >
            <Icon name="calendar" size={18} stroke={2} />Réserver
          </button>
          <button className="btn btn-ghost btn-block" style={{ marginTop: 10 }}>
            <Icon name="phone" size={16} />{d.phone}
          </button>
          <div className="tiny" style={{ textAlign: 'center', marginTop: 12 }}>Confirmation immédiate · Sans frais</div>
        </div>
      </div>
    </div>
  );
}
