'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { UsageEntry } from '@/lib/storage';
import { Cigarette, Leaf } from 'lucide-react';
import { useTheme } from '@/lib/theme-context';
import { getTodayString, getLocalDateString } from '@/lib/date-utils';

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

export function StatsCard({ usageData, substance }: StatsCardProps) {
  const { theme } = useTheme();
  const substanceData = usageData.filter((e) => e.substance === substance);

  // Calculate stats
  const today = new Date();
  const todayStr = getTodayString();
  const todayUsage = substanceData.find((e) => e.date === todayStr)?.count ?? 0;

  // Last 7 days
  const last7Days = substanceData.filter((e) => {
    const entryDate = new Date(e.date);
    const diff = (today.getTime() - entryDate.getTime()) / (1000 * 60 * 60 * 24);
    return diff <= 7 && diff >= 0;
  });
  const weekTotal = last7Days.reduce((sum, e) => sum + e.count, 0);
  const weekAverage = last7Days.length > 0 ? Math.round(weekTotal / last7Days.length) : 0;

  // Streak (days with 0 usage)
  let streak = 0;
  const sortedDates = substanceData
    .map((e) => e.date)
    .sort((a, b) => new Date(b).getTime() - new Date(a).getTime());

  for (let i = 0; i <= 30; i++) {
    const checkDate = new Date(today);
    checkDate.setDate(checkDate.getDate() - i);
    const dateStr = getLocalDateString(checkDate);
    const dayUsage = substanceData.find((e) => e.date === dateStr)?.count ?? -1;

    if (dayUsage === 0) {
      streak++;
    } else if (dayUsage > 0) {
      break;
    }
  }

  // Total tracked
  const totalUsage = substanceData.reduce((sum, e) => sum + e.count, 0);
  const totalDays = substanceData.length;

  const SubstanceIcon = substance === 'nicotine' ? Cigarette : Leaf;
  const substanceLabel = substance === 'nicotine' ? 'Nicotine' : 'Marijuana';
  const unitLabel = substance === 'nicotine' ? 'puffs' : 'hits';
  const iconColor = substance === 'nicotine' ? 'text-red-400' : 'text-green-400';
  const borderColor = substance === 'nicotine' ? 'border-red-500/30' : 'border-green-500/30';

  // Use darker gradients in light mode for better contrast
  const cardBackground = theme === 'light'
    ? substance === 'nicotine'
      ? 'linear-gradient(135deg, rgba(185, 28, 28, 0.85) 0%, rgba(127, 29, 29, 0.9) 100%)'
      : 'linear-gradient(135deg, rgba(22, 101, 52, 0.85) 0%, rgba(20, 83, 45, 0.9) 100%)'
    : substance === 'nicotine'
      ? 'linear-gradient(135deg, rgba(239, 68, 68, 0.2) 0%, rgba(127, 29, 29, 0.1) 100%)'
      : 'linear-gradient(135deg, rgba(34, 197, 94, 0.2) 0%, rgba(20, 83, 45, 0.1) 100%)';

  return (
    <Card
      className={`backdrop-blur-xl border ${borderColor} shadow-xl drop-shadow-lg hover-lift transition-all duration-300 overflow-hidden relative`}
      style={{ background: cardBackground }}
    >
      <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-white/5 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 pointer-events-none" />
      <CardHeader className="pb-2 relative z-10">
        <CardTitle className="flex items-center gap-2 text-white text-shadow-sm">
          <SubstanceIcon className={`h-5 w-5 ${iconColor}`} />
          <span>{substanceLabel} Stats</span>
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-2 gap-2 sm:gap-4">
          <div className="bg-white/10 p-3 sm:p-4 rounded-lg text-center hover:bg-white/15 transition-all duration-200 hover:scale-[1.02]">
            <p className="text-xl sm:text-2xl font-bold text-white">{todayUsage}</p>
            <p className="text-xs sm:text-sm text-white/70">Today</p>
          </div>
          <div className="bg-white/10 p-3 sm:p-4 rounded-lg text-center hover:bg-white/15 transition-all duration-200 hover:scale-[1.02]">
            <p className="text-xl sm:text-2xl font-bold text-white">{weekAverage}</p>
            <p className="text-xs sm:text-sm text-white/70">Daily Avg (7d)</p>
          </div>
          <div className="bg-white/10 p-3 sm:p-4 rounded-lg text-center hover:bg-white/15 transition-all duration-200 hover:scale-[1.02]">
            <p className="text-xl sm:text-2xl font-bold text-white">{streak}</p>
            <p className="text-xs sm:text-sm text-white/70">Free days</p>
          </div>
          <div className="bg-white/10 p-3 sm:p-4 rounded-lg text-center hover:bg-white/15 transition-all duration-200 hover:scale-[1.02]">
            <p className="text-xl sm:text-2xl font-bold text-white">{totalDays}</p>
            <p className="text-xs sm:text-sm text-white/70">Days tracked</p>
          </div>
        </div>

        {streak > 0 && (
          <div className={`mt-4 ${substance === 'nicotine' ? 'bg-gradient-to-r from-red-500/20 to-orange-500/20 border-red-500/30' : 'bg-gradient-to-r from-green-500/20 to-emerald-500/20 border-green-500/30'} p-4 rounded-xl text-center border backdrop-blur-sm`}>
            <p className="text-lg font-semibold text-white">{streak} day{streak > 1 ? 's' : ''} {substanceLabel.toLowerCase()}-free!</p>
            <p className="text-sm text-white/70">Keep up the great work!</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
