"use client";

import { useEffect, useState } from "react";
import { Loader2, MessageSquare, BarChart3, MapPin, ShieldCheck, X } from "lucide-react";

interface ReviewIntel {
  topTerms: Array<{ term: string; count: number }>;
  serviceFrequency: Array<{ service: string; mentions: number }>;
  locationMentions: Array<{ area: string; count: number }>;
  trustSignals: { expertise: number; quality: number; comparison: number };
  suggestReviewTopics: string[];
}

interface Props { locationId: string; locationName: string; onClose: () => void }

export default function ReviewIntelPanel({ locationId, locationName, onClose }: Props) {
  const [data, setData] = useState<ReviewIntel | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/gbp/locations/${locationId}/review-intel`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setData(d))
      .finally(() => setLoading(false));
  }, [locationId]);

  if (loading) return <div className="bg-white rounded-xl border border-slate-200 px-5 py-8 text-center"><Loader2 className="w-5 h-5 text-slate-400 animate-spin mx-auto" /></div>;
  if (!data) return null;

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between">
        <div className="flex items-center gap-2"><MessageSquare className="w-4 h-4 text-brand-600" /><h3 className="font-bold text-slate-800 text-sm">Review Intelligence: {locationName}</h3></div>
        <button onClick={onClose} className="p-1 rounded-md hover:bg-slate-100 text-slate-400"><X className="w-4 h-4" /></button>
      </div>

      <div className="px-5 py-4 grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Top terms (word cloud fallback) */}
        {data.topTerms.length > 0 && (
          <div>
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Most Mentioned Terms</p>
            <div className="flex flex-wrap gap-1.5">
              {data.topTerms.map((t) => {
                const size = t.count >= 10 ? "text-sm font-bold" : t.count >= 5 ? "text-xs font-semibold" : "text-[11px] font-medium";
                return <span key={t.term} className={`px-2 py-0.5 rounded-md bg-brand-50 text-brand-700 ${size}`}>{t.term} <span className="text-brand-400">{t.count}</span></span>;
              })}
            </div>
          </div>
        )}

        {/* Service frequency */}
        {data.serviceFrequency.length > 0 && (
          <div>
            <div className="flex items-center gap-1.5 mb-2"><BarChart3 className="w-3.5 h-3.5 text-violet-500" /><p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Services in Reviews</p></div>
            <div className="space-y-1.5">
              {data.serviceFrequency.slice(0, 8).map((s) => (
                <div key={s.service} className="flex items-center gap-2">
                  <span className="text-xs text-slate-700 w-32 truncate">{s.service}</span>
                  <div className="flex-1 h-1.5 bg-slate-100 rounded-full overflow-hidden"><div className="h-full bg-violet-500 rounded-full" style={{ width: `${Math.min(100, (s.mentions / Math.max(1, data.serviceFrequency[0]?.mentions ?? 1)) * 100)}%` }} /></div>
                  <span className="text-[10px] text-slate-500 tabular-nums">{s.mentions}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Location mentions */}
        {data.locationMentions.length > 0 && (
          <div>
            <div className="flex items-center gap-1.5 mb-2"><MapPin className="w-3.5 h-3.5 text-emerald-500" /><p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Area Mentions</p></div>
            <div className="flex flex-wrap gap-1.5">{data.locationMentions.map((l) => <span key={l.area} className="px-2 py-0.5 rounded-md bg-emerald-50 text-emerald-700 text-[11px] font-medium">{l.area} ({l.count})</span>)}</div>
          </div>
        )}

        {/* Trust signals */}
        <div>
          <div className="flex items-center gap-1.5 mb-2"><ShieldCheck className="w-3.5 h-3.5 text-amber-500" /><p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Trust Signals</p></div>
          <div className="grid grid-cols-3 gap-2">
            <div className="bg-amber-50 rounded-lg px-3 py-2 text-center"><p className="text-lg font-bold text-amber-700">{data.trustSignals.expertise}</p><p className="text-[9px] text-amber-600">Expertise</p></div>
            <div className="bg-green-50 rounded-lg px-3 py-2 text-center"><p className="text-lg font-bold text-green-700">{data.trustSignals.quality}</p><p className="text-[9px] text-green-600">Quality</p></div>
            <div className="bg-blue-50 rounded-lg px-3 py-2 text-center"><p className="text-lg font-bold text-blue-700">{data.trustSignals.comparison}</p><p className="text-[9px] text-blue-600">Comparison</p></div>
          </div>
        </div>
      </div>

      {/* Encourage review topics */}
      {data.suggestReviewTopics.length > 0 && (
        <div className="px-5 py-3 border-t border-slate-100 bg-brand-50/30">
          <p className="text-[10px] font-bold uppercase tracking-widest text-brand-600 mb-1.5">Encourage Reviews About</p>
          <div className="flex flex-wrap gap-1.5">{data.suggestReviewTopics.map((t) => <span key={t} className="px-2.5 py-1 rounded-lg bg-brand-600 text-white text-[11px] font-semibold">{t}</span>)}</div>
        </div>
      )}
    </div>
  );
}
