"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Crosshair, TrendingUp, ArrowUpRight, ArrowDownRight, Minus } from "lucide-react";

interface Keyword { keyword: string; position: number | null; change: number | null; url: string | null }
interface Data { total: number; avgPosition: number | null; top3: number; top10: number; keywords: Keyword[] }

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

  useEffect(() => {
    fetch(`/api/client-portal/rankings?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 || data.total === 0) return (
    <div className="text-center py-16">
      <Crosshair className="w-12 h-12 text-slate-200 mx-auto mb-3" />
      <p className="text-sm font-semibold text-slate-700">No keywords being tracked yet</p>
      <p className="text-xs text-slate-500 mt-1">Your agency will set up keyword tracking for you.</p>
    </div>
  );

  return (
    <div className="space-y-6 max-w-5xl">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Keyword Rankings</h1>
        <p className="text-slate-500 text-sm mt-1">{data.total} keywords tracked</p>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <SummaryCard label="Total" value={String(data.total)} />
        <SummaryCard label="Avg Position" value={data.avgPosition != null ? String(data.avgPosition) : "—"} />
        <SummaryCard label="Top 3" value={String(data.top3)} color="text-green-600" />
        <SummaryCard label="Top 10" value={String(data.top10)} color="text-blue-600" />
      </div>

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="border-b border-slate-100 bg-slate-50/80 text-[10px] font-bold uppercase tracking-widest text-slate-400">
            <th className="px-4 py-2.5 text-left">Keyword</th>
            <th className="px-4 py-2.5 text-center">Position</th>
            <th className="px-4 py-2.5 text-center">Change</th>
            <th className="px-4 py-2.5 text-left">URL</th>
          </tr></thead>
          <tbody>
            {data.keywords.map((kw) => (
              <tr key={kw.keyword} className="border-b border-slate-100 hover:bg-slate-50">
                <td className="px-4 py-2.5 font-medium text-slate-900">{kw.keyword}</td>
                <td className="px-4 py-2.5 text-center">
                  <span className={`text-lg font-bold tabular-nums ${posColor(kw.position)}`}>{kw.position ?? "—"}</span>
                </td>
                <td className="px-4 py-2.5 text-center">
                  {kw.change != null && kw.change > 0 ? <span className="flex items-center justify-center gap-0.5 text-green-600 font-bold text-xs"><ArrowUpRight className="w-3.5 h-3.5" />{kw.change}</span>
                   : kw.change != null && kw.change < 0 ? <span className="flex items-center justify-center gap-0.5 text-red-500 font-bold text-xs"><ArrowDownRight className="w-3.5 h-3.5" />{Math.abs(kw.change)}</span>
                   : <Minus className="w-3 h-3 text-slate-300 mx-auto" />}
                </td>
                <td className="px-4 py-2.5 text-xs text-slate-600 truncate max-w-[200px]">{kw.url || "—"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function posColor(pos: number | null): string {
  if (pos == null) return "text-slate-400";
  if (pos <= 3) return "text-green-600";
  if (pos <= 10) return "text-blue-600";
  if (pos <= 20) return "text-amber-600";
  return "text-red-500";
}

function SummaryCard({ label, value, color }: { label: string; value: string; color?: string }) {
  return (
    <div 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">{label}</p>
      <p className={`text-2xl font-bold tabular-nums ${color || "text-slate-900"}`}>{value}</p>
    </div>
  );
}
