"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { FileText, TrendingUp, AlertTriangle, Lightbulb, BarChart3 } from "lucide-react";

export default function ClientReportPage() {
  const { brandId } = useParams();
  const [report, setReport] = useState<Record<string, unknown> | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/client-portal/report?brandId=${brandId}&days=28`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => { if (d?.report) setReport(d.report); })
      .finally(() => setLoading(false));
  }, [brandId]);

  if (loading) return <div className="flex items-center justify-center h-64"><div className="w-8 h-8 border-4 border-slate-200 border-t-slate-600 rounded-full animate-spin" /></div>;
  if (!report) return <div className="text-center py-16 text-sm text-slate-400">No report data available yet.</div>;

  const exec = report.executiveSummary as { narrative?: string; healthScore?: number; topWin?: string; topConcern?: string; topOpportunity?: string; kpis?: Array<{ label: string; value: number; unit?: string; changePct?: number }> } | undefined;
  const wins = report.wins as { topPages?: Array<{ url: string; clicks: number }>; topKeywords?: Array<{ query: string; clicks: number }> } | undefined;

  return (
    <div className="space-y-6 max-w-5xl">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Performance Report</h1>
        <p className="text-slate-500 text-sm mt-1">Last 28 days</p>
      </div>

      {/* KPIs */}
      {exec?.kpis && exec.kpis.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {exec.kpis.slice(0, 4).map((kpi) => (
            <div key={kpi.label} className="bg-white rounded-xl border border-slate-200 px-5 py-4">
              <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">{kpi.label}</p>
              <p className="text-2xl font-bold text-slate-900">{kpi.value.toLocaleString()}{kpi.unit || ""}</p>
              {kpi.changePct != null && <p className={`text-xs font-medium mt-1 ${kpi.changePct >= 0 ? "text-green-600" : "text-red-500"}`}>{kpi.changePct >= 0 ? "+" : ""}{kpi.changePct.toFixed(1)}%</p>}
            </div>
          ))}
        </div>
      )}

      {/* Executive Summary */}
      {exec?.narrative && (
        <div className="bg-white rounded-xl border border-slate-200 px-6 py-5">
          <div className="flex items-center gap-2 mb-3"><FileText className="w-4 h-4 text-brand-600" /><h2 className="font-bold text-slate-800 text-sm">Executive Summary</h2></div>
          <p className="text-sm text-slate-700 leading-relaxed">{exec.narrative}</p>
        </div>
      )}

      {/* Highlights */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {exec?.topWin && (
          <div className="bg-green-50 border border-green-200 rounded-xl px-5 py-4">
            <div className="flex items-center gap-2 mb-2"><TrendingUp className="w-4 h-4 text-green-600" /><span className="text-xs font-bold uppercase tracking-widest text-green-700">Top Win</span></div>
            <p className="text-sm text-slate-700">{exec.topWin}</p>
          </div>
        )}
        {exec?.topConcern && (
          <div className="bg-amber-50 border border-amber-200 rounded-xl px-5 py-4">
            <div className="flex items-center gap-2 mb-2"><AlertTriangle className="w-4 h-4 text-amber-600" /><span className="text-xs font-bold uppercase tracking-widest text-amber-700">Concern</span></div>
            <p className="text-sm text-slate-700">{exec.topConcern}</p>
          </div>
        )}
        {exec?.topOpportunity && (
          <div className="bg-blue-50 border border-blue-200 rounded-xl px-5 py-4">
            <div className="flex items-center gap-2 mb-2"><Lightbulb className="w-4 h-4 text-blue-600" /><span className="text-xs font-bold uppercase tracking-widest text-blue-700">Opportunity</span></div>
            <p className="text-sm text-slate-700">{exec.topOpportunity}</p>
          </div>
        )}
      </div>

      {/* Top Pages */}
      {wins?.topPages && wins.topPages.length > 0 && (
        <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 gap-2"><BarChart3 className="w-4 h-4 text-brand-600" /><h2 className="font-bold text-slate-800 text-sm">Top Pages by Clicks</h2></div>
          <div className="divide-y divide-slate-100">
            {wins.topPages.slice(0, 10).map((p) => (
              <div key={p.url} className="px-5 py-2.5 flex items-center gap-4">
                <span className="text-xs font-mono text-brand-600 truncate flex-1">{p.url}</span>
                <span className="text-sm font-bold text-slate-900 tabular-nums">{p.clicks.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Top Keywords */}
      {wins?.topKeywords && wins.topKeywords.length > 0 && (
        <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 gap-2"><TrendingUp className="w-4 h-4 text-brand-600" /><h2 className="font-bold text-slate-800 text-sm">Top Keywords</h2></div>
          <div className="divide-y divide-slate-100">
            {wins.topKeywords.slice(0, 10).map((k) => (
              <div key={k.query} className="px-5 py-2.5 flex items-center gap-4">
                <span className="text-sm text-slate-800 flex-1">{k.query}</span>
                <span className="text-sm font-bold text-slate-900 tabular-nums">{k.clicks.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
