"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { TrendingUp, MousePointerClick, Eye, BarChart3, ShieldCheck, ChevronRight } from "lucide-react";

interface PortalPageCfg { enabled?: boolean; sections?: Record<string, boolean> }
interface DashboardData {
  gsc: { clicks: number; impressions: number; ctr: number; avgPosition: number };
  ga4: { sessions: number; conversions: number; users: number } | null;
  health: number | null;
  trackedKeywords: number;
  portal?: { portalConfig?: { pages?: { dashboard?: PortalPageCfg } } };
}

export default function ClientDashboard() {
  const { brandId } = useParams();
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/client-portal/dashboard?brandId=${brandId}`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setData(d))
      .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 (!data) return <div className="text-center py-16 text-sm text-slate-400">Unable to load dashboard data.</div>;

  const sec = data.portal?.portalConfig?.pages?.dashboard?.sections;
  const show = (id: string) => !sec || sec[id] !== false;

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

      {show("kpis") && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <KpiCard label="Organic Clicks" value={data.gsc.clicks.toLocaleString()} icon={MousePointerClick} color="text-green-600" />
          <KpiCard label="Impressions" value={data.gsc.impressions.toLocaleString()} icon={Eye} color="text-blue-600" />
          <KpiCard label="Sessions" value={data.ga4?.sessions.toLocaleString() ?? "—"} icon={BarChart3} color="text-violet-600" />
          {show("conversions") && <KpiCard label="Conversions" value={data.ga4?.conversions.toLocaleString() ?? "—"} icon={TrendingUp} color="text-amber-600" />}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {show("techIssues") && (
          <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
            <div className="flex items-center gap-2 mb-2"><ShieldCheck className="w-4 h-4 text-brand-600" /><span className="text-xs font-bold uppercase tracking-widest text-slate-400">Site Health</span></div>
            <p className="text-3xl font-bold text-slate-900">{data.health != null ? `${data.health}/100` : "—"}</p>
            <p className="text-xs text-slate-500 mt-1">Crawl health score</p>
          </div>
        )}
        <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
          <div className="flex items-center gap-2 mb-2"><TrendingUp className="w-4 h-4 text-brand-600" /><span className="text-xs font-bold uppercase tracking-widest text-slate-400">Avg Position</span></div>
          <p className="text-3xl font-bold text-slate-900">{data.gsc.avgPosition || "—"}</p>
          <p className="text-xs text-slate-500 mt-1">Google search position</p>
        </div>
        {show("rankSummary") && (
          <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
            <div className="flex items-center gap-2 mb-2"><BarChart3 className="w-4 h-4 text-brand-600" /><span className="text-xs font-bold uppercase tracking-widest text-slate-400">Keywords</span></div>
            <p className="text-3xl font-bold text-slate-900">{data.trackedKeywords}</p>
            <p className="text-xs text-slate-500 mt-1">Keywords tracked</p>
          </div>
        )}
      </div>

      <Link href={`/client/${brandId}/report`} className="flex items-center justify-center gap-2 px-6 py-3 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 w-fit">
        View Full Report <ChevronRight className="w-4 h-4" />
      </Link>
    </div>
  );
}

function KpiCard({ label, value, icon: Icon, color }: { label: string; value: string; icon: typeof TrendingUp; color: string }) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
      <div className="flex items-center justify-between mb-2">
        <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">{label}</span>
        <Icon className={`w-4 h-4 ${color}`} />
      </div>
      <p className="text-3xl font-bold text-slate-900 tabular-nums">{value}</p>
    </div>
  );
}
