"use client";

import { useState, useEffect } from "react";
import { Loader2, TrendingUp } from "lucide-react";
import { ResponsiveContainer, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip } from "recharts";

interface Snapshot { totalBacklinks: number; totalDomains: number; snapshotDate: string }

export default function TrendChart({ brandId }: { brandId: string }) {
  const [snapshots, setSnapshots] = useState<Snapshot[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/backlinks/snapshots?brandId=${brandId}`)
      .then((r) => r.ok ? r.json() : { snapshots: [] })
      .then((d) => setSnapshots(d.snapshots || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [brandId]);

  if (loading) return <div className="bg-white rounded-xl border border-slate-200 p-5 flex justify-center py-12"><Loader2 className="w-5 h-5 animate-spin text-slate-300" /></div>;
  if (snapshots.length < 2) return null;

  const data = snapshots.map((s) => ({
    date: new Date(s.snapshotDate).toLocaleDateString("en-US", { month: "short", day: "numeric" }),
    backlinks: s.totalBacklinks,
    domains: s.totalDomains,
  }));

  return (
    <div className="bg-white rounded-xl border border-slate-200 p-5">
      <div className="flex items-center gap-2 mb-4">
        <TrendingUp className="w-4 h-4 text-teal-600" />
        <h3 className="text-sm font-bold text-slate-800">Backlink Growth</h3>
      </div>
      <ResponsiveContainer width="100%" height={200} minWidth={0}>
        <LineChart data={data}>
          <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
          <XAxis dataKey="date" tick={{ fontSize: 10 }} stroke="#94a3b8" />
          <YAxis tick={{ fontSize: 10 }} stroke="#94a3b8" width={40} />
          <Tooltip contentStyle={{ fontSize: 12 }} />
          <Line type="monotone" dataKey="backlinks" stroke="#0D9488" strokeWidth={2} dot={{ r: 3 }} name="Backlinks" />
          <Line type="monotone" dataKey="domains" stroke="#6366F1" strokeWidth={1.5} strokeDasharray="4 3" dot={false} name="Domains" />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}
