"use client";

/**
 * Audit Health Trend — Line chart of technical audit scores over time.
 * Used on the /technical-audit page.
 */

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

interface HistoryEntry { healthScore: number; errorCount: number; warningCount: number; totalIssues: number; auditedAt: string }

export default function AuditHealthTrend() {
  const { brand } = useBrand();
  const [history, setHistory] = useState<HistoryEntry[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/technical-audit/history?brandId=${brand.id}`)
      .then((r) => r.ok ? r.json() : { history: [] })
      .then((d) => setHistory(d.history || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [brand.id]);

  if (loading) return <div className="py-6 text-center"><Loader2 className="w-5 h-5 animate-spin text-slate-300 mx-auto" /></div>;
  if (history.length < 2) return null; // Need at least 2 data points

  const data = history.map((h) => ({
    date: new Date(h.auditedAt).toLocaleDateString("en-US", { month: "short", day: "numeric" }),
    score: h.healthScore,
    errors: h.errorCount,
  }));

  const latest = history[history.length - 1];
  const prev = history[history.length - 2];
  const diff = latest.healthScore - prev.healthScore;

  return (
    <div className="bg-white rounded-xl border border-slate-200 p-5">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <TrendingUp className="w-4 h-4 text-teal-600" />
          <h3 className="text-sm font-bold text-slate-800">Health Score Trend</h3>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-lg font-bold text-slate-900">{latest.healthScore}</span>
          {diff !== 0 && (
            <span className={`text-xs font-semibold ${diff > 0 ? "text-green-600" : "text-red-600"}`}>
              {diff > 0 ? "+" : ""}{diff} pts
            </span>
          )}
        </div>
      </div>
      <ResponsiveContainer width="100%" height={160} minWidth={0}>
        <LineChart data={data}>
          <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
          <XAxis dataKey="date" tick={{ fontSize: 10 }} stroke="#94a3b8" />
          <YAxis domain={[0, 100]} tick={{ fontSize: 10 }} stroke="#94a3b8" width={30} />
          <Tooltip contentStyle={{ fontSize: 12 }} />
          <Line type="monotone" dataKey="score" stroke="#0D9488" strokeWidth={2} dot={{ r: 3 }} name="Health Score" />
          <Line type="monotone" dataKey="errors" stroke="#EF4444" strokeWidth={1.5} strokeDasharray="4 3" dot={false} name="Errors" />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}
