"use client";

import { useEffect, useState } from "react";
import { Loader2, Sparkles, CheckCircle2, AlertTriangle, Target, X } from "lucide-react";

interface GeoData {
  geoScore: number; strengths: string[]; weaknesses: string[];
  recommendations: Array<{ action: string; impact: string; reason: string }>;
  suggestedSchema: string[]; reviewStrategy: string; contentSuggestions: string[];
}

const IMPACT_CLS: Record<string, string> = { high: "bg-red-50 text-red-700 border-red-200", medium: "bg-amber-50 text-amber-700 border-amber-200", low: "bg-blue-50 text-blue-700 border-blue-200" };

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

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

  useEffect(() => {
    fetch(`/api/gbp/locations/${locationId}/geo`, { method: "POST" })
      .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-brand-200 px-5 py-12 text-center">
      <Loader2 className="w-6 h-6 text-brand-500 animate-spin mx-auto mb-2" />
      <p className="text-xs text-slate-500">Analyzing AI search readiness for {locationName}...</p>
    </div>
  );
  if (!data) return null;

  const scoreColor = data.geoScore >= 70 ? "#16a34a" : data.geoScore >= 40 ? "#f59e0b" : "#ef4444";

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

      {/* Score + summary */}
      <div className="px-5 py-5 flex items-center gap-6">
        <div className="relative w-20 h-20 shrink-0">
          <svg viewBox="0 0 64 64" className="w-20 h-20 -rotate-90">
            <circle cx="32" cy="32" r="27" fill="none" stroke="#e2e8f0" strokeWidth="5" />
            <circle cx="32" cy="32" r="27" fill="none" stroke={scoreColor} strokeWidth="5" strokeLinecap="round" strokeDasharray={`${(data.geoScore / 100) * 169.6} 169.6`} />
          </svg>
          <div className="absolute inset-0 flex flex-col items-center justify-center">
            <span className="text-xl font-bold text-slate-900">{data.geoScore}</span>
            <span className="text-[9px] text-slate-400">/100</span>
          </div>
        </div>
        <div className="flex-1 space-y-2">
          {data.strengths.slice(0, 3).map((s, i) => (
            <div key={i} className="flex items-start gap-2"><CheckCircle2 className="w-3.5 h-3.5 text-green-500 mt-0.5 shrink-0" /><span className="text-xs text-slate-700">{s}</span></div>
          ))}
          {data.weaknesses.slice(0, 2).map((w, i) => (
            <div key={i} className="flex items-start gap-2"><AlertTriangle className="w-3.5 h-3.5 text-amber-500 mt-0.5 shrink-0" /><span className="text-xs text-slate-700">{w}</span></div>
          ))}
        </div>
      </div>

      {/* Recommendations */}
      {data.recommendations.length > 0 && (
        <div className="px-5 py-4 border-t border-slate-100">
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">AI Search Recommendations</p>
          <div className="space-y-2">
            {data.recommendations.map((r, i) => (
              <div key={i} className="flex items-start gap-2">
                <span className={`text-[9px] font-bold uppercase tracking-wider rounded-full px-2 py-0.5 border shrink-0 mt-0.5 ${IMPACT_CLS[r.impact] || IMPACT_CLS.medium}`}>{r.impact}</span>
                <div><p className="text-xs font-semibold text-slate-900">{r.action}</p><p className="text-[11px] text-slate-500">{r.reason}</p></div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Schema + content suggestions */}
      <div className="px-5 py-4 border-t border-slate-100 grid grid-cols-2 gap-4">
        {data.suggestedSchema.length > 0 && (
          <div>
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">Suggested Schema</p>
            <div className="flex flex-wrap gap-1">{data.suggestedSchema.map((s) => <span key={s} className="px-2 py-0.5 rounded-md bg-violet-50 text-violet-700 text-[10px] font-semibold">{s}</span>)}</div>
          </div>
        )}
        {data.contentSuggestions.length > 0 && (
          <div>
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">Content for AI Pickup</p>
            <ul className="space-y-1">{data.contentSuggestions.slice(0, 3).map((c, i) => <li key={i} className="text-[11px] text-slate-600 flex items-start gap-1"><Target className="w-3 h-3 text-brand-500 mt-0.5 shrink-0" />{c}</li>)}</ul>
          </div>
        )}
      </div>

      {data.reviewStrategy && (
        <div className="px-5 py-3 border-t border-slate-100 bg-slate-50">
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Review Strategy</p>
          <p className="text-xs text-slate-700">{data.reviewStrategy}</p>
        </div>
      )}
    </div>
  );
}
