"use client";

import { TrendingUp } from "lucide-react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  CartesianGrid,
} from "recharts";
import { TrendScore } from "@/lib/types";
import { formatDate } from "@/lib/utils";

interface TrendChartProps {
  data?: TrendScore[];
}

export function TrendChart({ data }: TrendChartProps) {
  const chartData = data?.map((d) => ({
    date: new Date(d.score_date).toLocaleDateString("en-US", { month: "short", day: "numeric" }),
    score: Math.round(d.composite_score),
    news: d.newsapi_count,
    gnews: d.gnews_count,
  })) ?? [];

  const latest = data?.[data.length - 1]?.composite_score;

  return (
    <div className="bg-card border border-border rounded-lg p-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-semibold text-sm flex items-center gap-2">
          <TrendingUp className="w-4 h-4" />
          Public Interest
        </h3>
        {latest !== undefined && (
          <span className="text-2xl font-bold tabular-nums">{Math.round(latest)}</span>
        )}
      </div>

      {chartData.length === 0 ? (
        <p className="text-xs text-muted-foreground italic text-center py-8">
          Trend data not yet available.
        </p>
      ) : (
        <ResponsiveContainer width="100%" height={180}>
          <LineChart data={chartData} margin={{ top: 4, right: 4, left: -20, bottom: 0 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
            <XAxis
              dataKey="date"
              tick={{ fontSize: 10, fill: "hsl(var(--muted-foreground))" }}
              tickLine={false}
            />
            <YAxis
              domain={[0, 100]}
              tick={{ fontSize: 10, fill: "hsl(var(--muted-foreground))" }}
              tickLine={false}
            />
            <Tooltip
              contentStyle={{
                backgroundColor: "hsl(var(--card))",
                border: "1px solid hsl(var(--border))",
                borderRadius: "6px",
                fontSize: "12px",
              }}
            />
            <Line
              type="monotone"
              dataKey="score"
              stroke="hsl(var(--primary))"
              strokeWidth={2}
              dot={false}
              name="Zeitgeist Score"
            />
          </LineChart>
        </ResponsiveContainer>
      )}

      <div className="mt-3 flex gap-4 text-xs text-muted-foreground">
        <span>Score: 0–100 composite</span>
        <span>NewsAPI + Google News + Trends</span>
      </div>
    </div>
  );
}
