'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { User } from '@/lib/session';
import { fetchUsageData, UsageEntry } from '@/lib/storage';
import { UserHeader } from './UserHeader';
import { StatsCard } from './StatsCard';
import { UsageTrendGraph } from './UsageTrendGraph';
import { Cigarette, Leaf } from 'lucide-react';
import { useTheme } from '@/lib/theme-context';

interface SubstanceTrackingPageProps {
  user: User;
  substance: 'nicotine' | 'weed';
}

export function SubstanceTrackingPage({ user, substance }: SubstanceTrackingPageProps) {
  const [usageData, setUsageData] = useState<UsageEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const { theme } = useTheme();

  const loadData = useCallback(async () => {
    const usage = await fetchUsageData();
    setUsageData(usage);
    setIsLoading(false);
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const todayCount = useMemo(() => {
    const today = new Date().toISOString().split('T')[0];
    const entry = usageData.find((e) => e.date === today && e.substance === substance);
    return entry?.count ?? 0;
  }, [usageData, substance]);

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

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-pulse text-lg text-white">Loading...</div>
      </div>
    );
  }

  const pageBackground = theme === 'dark'
    ? 'linear-gradient(135deg, #0a0a14 0%, #141e3c 50%, #0f1932 100%)'
    : 'linear-gradient(135deg, #ffffff 0%, #f0f4f8 50%, #e8ecf0 100%)';

  return (
    <div className="min-h-screen" style={{ background: pageBackground }}>
      <UserHeader user={user} />

      <main className="container mx-auto px-4 py-8">
        {/* Substance Header */}
        <div className={`mb-6 sm:mb-8 p-4 sm:p-6 rounded-xl bg-gradient-to-r ${gradientColors} border ${borderColor} backdrop-blur-sm shadow-lg opacity-0 animate-fade-in-down`}>
          <div className="flex items-center gap-3 sm:gap-4">
            <div className={`p-2 sm:p-3 rounded-full bg-background/50 ${iconColor} transition-transform duration-300 hover:scale-110`}>
              <SubstanceIcon className="h-6 w-6 sm:h-8 sm:w-8" />
            </div>
            <div>
              <h1 className={`text-2xl sm:text-3xl font-bold ${theme === 'light' ? 'text-gray-900' : 'text-white'}`}>{substanceLabel} Tracking</h1>
              <p className={`mt-1 text-sm sm:text-base ${theme === 'light' ? 'text-gray-700' : 'text-white/70'}`}>Monitor your {substanceLabel.toLowerCase()} usage and progress</p>
            </div>
          </div>
        </div>

        {/* Today's Status Message */}
        <div className="mb-6 sm:mb-8 text-center opacity-0 animate-fade-in delay-100">
          {todayCount === 0 ? (
            <p className={`text-xl sm:text-2xl font-medium ${theme === 'light' ? 'text-green-600' : 'text-green-400'}`}>
              Great job, nothing yet!
            </p>
          ) : (
            <p className={`text-xl sm:text-2xl font-medium ${theme === 'light' ? 'text-gray-900' : 'text-white'}`}>
              {todayCount} {todayCount === 1 ? (substance === 'nicotine' ? 'puff' : 'hit') : unitLabel} recorded, you got this!
            </p>
          )}
        </div>

        {/* Inspirational Message */}
        <div className="mb-6 sm:mb-8 text-center opacity-0 animate-fade-in delay-200">
          <p className={`text-lg sm:text-xl font-light italic ${theme === 'light' ? 'text-gray-500' : 'text-white/60'}`}>
            &quot;One day at a time...&quot;
          </p>
        </div>

        {/* Stats and Graph */}
        <div className="grid gap-6 md:grid-cols-2">
          <div className="opacity-0 animate-fade-in-up delay-200">
            <StatsCard usageData={usageData} substance={substance} />
          </div>
          <div className="opacity-0 animate-slide-in-right delay-300">
            <UsageTrendGraph usageData={usageData} substance={substance} />
          </div>
        </div>
      </main>
    </div>
  );
}
