'use client';

import { useEffect, useState } from 'react';
import { Area, AreaChart, CartesianGrid, XAxis } from 'recharts';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from '@/components/ui/chart';
import { cn } from '@/lib/utils';

const chartConfig = {
  players: {
    label: 'Players',
    color: 'hsl(var(--chart-1))',
  },
} satisfies ChartConfig;

interface ChartData {
  date: string;
  players: number;
}

interface PlayerActivityChartProps {
  className?: string;
}

export function PlayerActivityChart({ className }: PlayerActivityChartProps = {}) {
  const [chartData, setChartData] = useState<ChartData[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Generate sample data for the last 7 days
    // In a real implementation, this would fetch from Plan API
    const generateData = () => {
      const data: ChartData[] = [];
      const now = new Date();

      for (let i = 6; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);

        data.push({
          date: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
          players: Math.floor(Math.random() * 5) + 1, // Random for demo
        });
      }

      return data;
    };

    setChartData(generateData());
    setLoading(false);
  }, []);

  if (loading) {
    return (
      <div className="h-[200px] flex items-center justify-center text-muted-foreground text-sm">
        Loading chart...
      </div>
    );
  }

  const peakPlayers = chartData.reduce((max, entry) => Math.max(max, entry.players), 0);
  const averagePlayers =
    chartData.length > 0
      ? Math.round(
          chartData.reduce((sum, entry) => sum + entry.players, 0) / chartData.length
        )
      : 0;
  const latestPlayers =
    chartData.length > 0 ? chartData[chartData.length - 1].players : 0;

  return (
    <Card
      className={cn(
        "rounded-2xl border border-border bg-card text-card-foreground shadow-lg",
        className
      )}
    >
      <CardHeader className="p-0 pb-4">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div>
            <CardTitle className="text-sm font-semibold">Player Activity</CardTitle>
            <CardDescription className="text-xs text-muted-foreground">
              Last 7 days
            </CardDescription>
          </div>
          <div className="flex flex-wrap items-center gap-3 text-xs uppercase tracking-[0.3em] text-muted-foreground">
            <span>
              Peak<span className="ml-1 font-semibold text-foreground">{peakPlayers}</span>
            </span>
            <span>
              Average
              <span className="ml-1 font-semibold text-foreground">
                {averagePlayers}
              </span>
            </span>
            <span>
              Latest
              <span className="ml-1 font-semibold text-foreground">{latestPlayers}</span>
            </span>
          </div>
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <ChartContainer
          config={chartConfig}
          className="aspect-auto h-[220px] w-full rounded-xl border border-border/60 bg-background/95 p-4"
        >
          <AreaChart
            accessibilityLayer
            data={chartData}
            margin={{
              left: 12,
              right: 12,
              top: 12,
              bottom: 12,
            }}
          >
            <defs>
              <linearGradient id="players-gradient" x1="0" x2="0" y1="0" y2="1">
                <stop offset="5%" stopColor="hsl(var(--chart-1))" stopOpacity={0.6} />
                <stop offset="95%" stopColor="hsl(var(--chart-1))" stopOpacity={0.05} />
              </linearGradient>
            </defs>
            <CartesianGrid
              vertical={false}
              strokeDasharray="4 4"
              stroke="rgba(148, 163, 184, 0.35)"
            />
            <XAxis
              dataKey="date"
              tickLine={false}
              axisLine={false}
              tickMargin={8}
              tickFormatter={(value) => value}
              tick={{ fill: 'hsl(var(--muted-foreground))', fontSize: 12, fontWeight: 500 }}
            />
            <ChartTooltip
              cursor={false}
              content={<ChartTooltipContent indicator="line" />}
            />
            <Area
              dataKey="players"
              type="natural"
              fill="url(#players-gradient)"
              stroke="var(--color-players)"
              strokeWidth={2.5}
            />
          </AreaChart>
        </ChartContainer>
      </CardContent>
    </Card>
  );
}
