'use client';

import { useMemo } from 'react';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Area,
  AreaChart,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { UsageEntry } from '@/lib/storage';

interface UsageTrendGraphProps {
  usageData: UsageEntry[];
  substance: 'nicotine' | 'weed';
}

export function UsageTrendGraph({ usageData, substance }: UsageTrendGraphProps) {
  const chartData = useMemo(() => {
    const substanceData = usageData.filter((e) => e.substance === substance);
    const today = new Date();
    const last30Days: { date: string; count: number; label: string }[] = [];

    for (let i = 29; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      const entry = substanceData.find((e) => e.date === dateStr);
      last30Days.push({
        date: dateStr,
        count: entry?.count ?? 0,
        label: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
      });
    }

    return last30Days;
  }, [usageData, substance]);

  const substanceColor = substance === 'nicotine' ? '#ef4444' : '#22c55e';
  const substanceLabel = substance === 'nicotine' ? 'Nicotine' : 'Marijuana';

  const average = useMemo(() => {
    const total = chartData.reduce((sum, d) => sum + d.count, 0);
    const daysWithData = chartData.filter((d) => d.count > 0).length;
    return daysWithData > 0 ? Math.round(total / daysWithData) : 0;
  }, [chartData]);

  const trend = useMemo(() => {
    const firstHalf = chartData.slice(0, 15);
    const secondHalf = chartData.slice(15);
    const firstAvg = firstHalf.reduce((sum, d) => sum + d.count, 0) / 15;
    const secondAvg = secondHalf.reduce((sum, d) => sum + d.count, 0) / 15;

    if (secondAvg < firstAvg * 0.9) return 'decreasing';
    if (secondAvg > firstAvg * 1.1) return 'increasing';
    return 'stable';
  }, [chartData]);

  return (
    <Card className="bg-card/80 backdrop-blur-xl shadow-xl drop-shadow-lg hover-lift transition-all duration-300 border-white/10">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>{substanceLabel} Usage Trend</span>
          <span className="text-sm font-normal text-muted-foreground">
            Last 30 days
          </span>
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-[300px] w-full">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={chartData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
              <defs>
                <linearGradient id={`gradient-${substance}`} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={substanceColor} stopOpacity={0.3} />
                  <stop offset="95%" stopColor={substanceColor} stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.1)" />
              <XAxis
                dataKey="label"
                stroke="rgba(255,255,255,0.5)"
                fontSize={12}
                tickLine={false}
                interval="preserveStartEnd"
              />
              <YAxis
                stroke="rgba(255,255,255,0.5)"
                fontSize={12}
                tickLine={false}
                axisLine={false}
              />
              <Tooltip
                contentStyle={{
                  backgroundColor: 'rgba(0,0,0,0.8)',
                  border: 'none',
                  borderRadius: '8px',
                  color: 'white',
                }}
                labelStyle={{ color: 'rgba(255,255,255,0.7)' }}
              />
              <Area
                type="monotone"
                dataKey="count"
                stroke={substanceColor}
                strokeWidth={2}
                fill={`url(#gradient-${substance})`}
                name={substance === 'nicotine' ? 'Puffs' : 'Hits'}
              />
            </AreaChart>
          </ResponsiveContainer>
        </div>

        <div className="mt-4 grid grid-cols-2 gap-4">
          <div className="bg-muted/50 p-3 rounded-lg text-center hover:bg-muted/70 transition-all duration-200 hover:scale-[1.02]">
            <p className="text-2xl font-bold">{average}</p>
            <p className="text-sm text-muted-foreground">Daily Average</p>
          </div>
          <div className="bg-muted/50 p-3 rounded-lg text-center hover:bg-muted/70 transition-all duration-200 hover:scale-[1.02]">
            <p className="text-2xl font-bold capitalize">{trend}</p>
            <p className="text-sm text-muted-foreground">
              {trend === 'decreasing' ? 'Great progress!' : trend === 'increasing' ? 'Stay strong!' : 'Holding steady'}
            </p>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
