'use client';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { QuitPlan, UsageEntry } from '@/lib/storage';
import { Target, TrendingDown } from 'lucide-react';
import { useTheme } from '@/lib/theme-context';

interface QuitPlanCardProps {
  plan: QuitPlan | null;
  onGeneratePlan: () => void;
  usageData: UsageEntry[];
}

export function QuitPlanCard({
  plan,
  onGeneratePlan,
  usageData,
}: QuitPlanCardProps) {
  const { theme } = useTheme();

  // Count unique days with any logged data
  const uniqueDaysWithData = new Set(usageData.map(e => e.date)).size;
  const daysRemaining = Math.max(0, 7 - uniqueDaysWithData);
  const hasEnoughData = uniqueDaysWithData >= 7;

  // Calculate current average
  const totalUsage = usageData.reduce((sum, e) => sum + e.count, 0);
  const currentAverage = uniqueDaysWithData > 0 ? Math.round(totalUsage / uniqueDaysWithData) : 0;

  // Yellow gradient for tracking phase (darker in light mode)
  const yellowBackground = theme === 'light'
    ? 'linear-gradient(135deg, rgba(161, 98, 7, 0.85) 0%, rgba(133, 77, 14, 0.9) 100%)'
    : 'linear-gradient(135deg, rgba(234, 179, 8, 0.2) 0%, rgba(202, 138, 4, 0.15) 100%)';

  // Pink gradient for active plan (darker in light mode)
  const pinkBackground = theme === 'light'
    ? 'linear-gradient(135deg, rgba(157, 23, 77, 0.85) 0%, rgba(131, 24, 67, 0.9) 100%)'
    : 'linear-gradient(135deg, rgba(236, 72, 153, 0.2) 0%, rgba(219, 39, 119, 0.15) 100%)';

  if (!plan) {
    return (
      <Card className="backdrop-blur-xl shadow-xl drop-shadow-lg border-yellow-500/40 hover-lift transition-all duration-300 overflow-hidden relative" style={{
        background: yellowBackground
      }}>
        <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-yellow-500/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 pointer-events-none" />
        <CardHeader className="relative z-10">
          <CardTitle className="flex items-center gap-2 text-white text-shadow-sm">
            <Target className="h-5 w-5 text-yellow-400" />
            Your Personalized Plan
          </CardTitle>
          <CardDescription className="text-white/70">
            We&apos;re tracking your usage to build your custom quit plan
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4 relative z-10">
          <div className="bg-yellow-500/20 border border-yellow-500/30 p-4 rounded-xl backdrop-blur-sm">
            <div className="flex justify-between items-center mb-3">
              <span className="text-sm font-medium text-white">Tracking Progress</span>
              <span className="text-sm text-yellow-300 font-bold">
                {daysRemaining > 0 ? `${daysRemaining} days left` : 'Ready!'}
              </span>
            </div>
            <div className="w-full bg-white/10 rounded-full h-3 overflow-hidden">
              <div
                className="bg-gradient-to-r from-yellow-400 to-yellow-500 h-3 rounded-full transition-all duration-700 ease-out"
                style={{ width: `${Math.min(100, (uniqueDaysWithData / 7) * 100)}%` }}
              />
            </div>
            <p className="text-xs text-white/60 mt-2 text-center">
              {uniqueDaysWithData} of 7 days tracked
            </p>
          </div>

          {hasEnoughData ? (
            <div className="space-y-3">
              <p className="text-sm text-white text-center">
                Great work! Your average daily usage is{' '}
                <strong className="text-yellow-300">{currentAverage}</strong> per day.
              </p>
              <Button onClick={onGeneratePlan} className="w-full bg-yellow-500 hover:bg-yellow-600 text-black font-semibold transition-all duration-300 hover:scale-[1.02] active:scale-[0.98]">
                <TrendingDown className="mr-2 h-4 w-4" />
                Generate My Quit Plan
              </Button>
            </div>
          ) : (
            <div className="text-center space-y-2">
              <p className="text-sm text-white">
                Log your usage each day. After 7 days, we&apos;ll create a personalized plan to help you reduce by <strong className="text-yellow-300">25% each week</strong>.
              </p>
              <p className="text-xs text-white/60">
                Your plan will be tailored to your habits
              </p>
            </div>
          )}
        </CardContent>
      </Card>
    );
  }

  const startDate = new Date(plan.startDate);
  const today = new Date();
  const weekNumber = Math.floor(
    (today.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24 * 7)
  ) + 1;
  const totalWeeks = plan.weeklyTargets.length;
  const currentTarget = weekNumber <= totalWeeks ? plan.weeklyTargets[weekNumber - 1] : 0;

  return (
    <Card className="backdrop-blur-xl shadow-xl drop-shadow-lg border-pink-500/40 hover-lift transition-all duration-300 overflow-hidden relative" style={{
      background: pinkBackground
    }}>
      <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-pink-500/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 pointer-events-none" />
      <CardHeader className="relative z-10">
        <CardTitle className="flex items-center gap-2 text-white text-shadow-sm">
          <TrendingDown className="h-5 w-5 text-pink-400" />
          Your Quit Plan
        </CardTitle>
        <CardDescription className="text-white/70">
          Week {Math.min(weekNumber, totalWeeks)} of {totalWeeks} - 25% weekly reduction
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4 relative z-10">
        <div className="bg-gradient-to-br from-pink-500/25 to-pink-600/20 border border-pink-500/40 p-5 rounded-xl text-center backdrop-blur-sm">
          <p className="text-sm text-white/70 mb-1">This week&apos;s daily target</p>
          <p className="text-5xl font-bold text-pink-300 text-shadow">
            {currentTarget !== null && currentTarget > 0 ? currentTarget : '0'}
          </p>
          <p className="text-sm text-white/60">per day</p>
        </div>

        <div className="space-y-2 relative z-10">
          <p className="text-sm font-medium text-white">Weekly targets:</p>
          <div className="grid grid-cols-4 gap-2">
            {plan.weeklyTargets.map((target, index) => (
              <div
                key={index}
                className={`text-center p-2 rounded-lg transition-all duration-200 hover:scale-105 ${
                  index + 1 === weekNumber
                    ? 'bg-gradient-to-br from-pink-500 to-pink-600 text-white shadow-lg shadow-pink-500/30'
                    : index + 1 < weekNumber
                    ? 'bg-pink-900/50 text-pink-200'
                    : 'bg-white/10 text-white/60'
                }`}
              >
                <p className="text-xs">Week {index + 1}</p>
                <p className="font-bold">{target}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="text-sm text-white/70 bg-white/5 p-3 rounded-lg">
          <p>
            <strong className="text-white">Started at:</strong> {plan.baselineAverage}/day
          </p>
          <p>
            <strong className="text-white">Goal:</strong> Quit by {new Date(plan.endDate).toLocaleDateString()}
          </p>
        </div>
      </CardContent>
    </Card>
  );
}
