'use client';

import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import React from 'react';
import { User } from '@/lib/session';
import {
  fetchPreferences,
  fetchUsageData,
  savePreferencesAsync,
  saveUsageEntryAsync,
  shouldShowUsagePrompt,
  markPromptShown,
  generateQuitPlan,
  fetchAchievements,
  fetchSavingsConfig,
  saveSavingsConfig,
  unlockAchievement,
  checkBadgeEligibility,
  UserPreferences,
  UsageEntry,
  Achievement,
  SavingsConfig,
  BADGE_DEFINITIONS,
  BadgeDefinition,
} from '@/lib/storage';
import { UserHeader } from './UserHeader';
import { SetupWizard } from './SetupWizard';
import { UsageCalendar } from './UsageCalendar';
import { StatsCard } from './StatsCard';
import { UnifiedQuitPlanCard } from './UnifiedQuitPlanCard';
import { AchievementsCard } from './AchievementsCard';
import { CelebrationAnimation } from './CelebrationAnimation';
import { HealthTimelineCard } from './HealthTimelineCard';
import { SavingsTrackerCard } from './SavingsTrackerCard';
import { MoodTracker } from './MoodTracker';
import { ScrollWheelLogger } from './ScrollWheelLogger';
import { UsageLoggerDropUp } from './UsageLoggerDropUp';
import { VersionUpdateModal } from './VersionUpdateModal';
import { Button } from '@/components/ui/button';
import { PlusCircle, ChevronLeft, ChevronRight, X } from 'lucide-react';
import { useTheme } from '@/lib/theme-context';
import { getTodayString } from '@/lib/date-utils';


interface DashboardProps {
  user: User;
}

export function Dashboard({ user }: DashboardProps) {
  const [preferences, setPreferences] = useState<UserPreferences | null>(null);
  const [usageData, setUsageData] = useState<UsageEntry[]>([]);
  const [achievements, setAchievements] = useState<Achievement[]>([]);
  const [savingsConfig, setSavingsConfig] = useState<SavingsConfig | null>(null);
  const [showSetup, setShowSetup] = useState(false);
  const [showCelebration, setShowCelebration] = useState(false);
  const [isSubstancePickerOpen, setIsSubstancePickerOpen] = useState(false);
  const [activeLoggingSubstance, setActiveLoggingSubstance] = useState<'nicotine' | 'weed' | null>(null);
  const [newBadge, setNewBadge] = useState<BadgeDefinition | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [refreshKey, setRefreshKey] = useState(0);
  const [currentPage, setCurrentPage] = useState(0);
  const [modalOpenCount, setModalOpenCount] = useState(0);
  const swipeContainerRef = useRef<HTMLDivElement>(null);
  const { theme } = useTheme();

  const isModalOpen = modalOpenCount > 0 || showSetup || showCelebration;
  const isNavHidden = isModalOpen || isSubstancePickerOpen || !!activeLoggingSubstance;

  const handleModalStateChange = useCallback((isOpen: boolean) => {
    setModalOpenCount(prev => isOpen ? prev + 1 : Math.max(0, prev - 1));
  }, []);

  const handleScroll = useCallback(() => {
    if (!swipeContainerRef.current) return;
    const scrollLeft = swipeContainerRef.current.scrollLeft;
    const width = swipeContainerRef.current.offsetWidth;
    const page = Math.round(scrollLeft / width);
    if (page !== currentPage) {
      setCurrentPage(page);
    }
  }, [currentPage]);

  const scrollToPage = (pageIndex: number) => {
    if (!swipeContainerRef.current) return;
    const width = swipeContainerRef.current.offsetWidth;
    swipeContainerRef.current.scrollTo({
      left: pageIndex * width,
      behavior: 'smooth'
    });
  };

  const loadData = useCallback(async () => {
    const [prefs, usage, achvs, savings] = await Promise.all([
      fetchPreferences(),
      fetchUsageData(),
      fetchAchievements(),
      fetchSavingsConfig(),
    ]);
    setPreferences(prefs);
    setUsageData(usage);
    setAchievements(achvs);
    setSavingsConfig(savings);
    console.log('[Dashboard] Loaded prefs:', prefs);
    setRefreshKey(prev => prev + 1);
    return { prefs, usage, achvs };
  }, []);

  const checkAndUnlockAchievements = useCallback(async (
    usage: UsageEntry[],
    prefs: UserPreferences,
    currentAchievements: Achievement[]
  ) => {
    // Current unlocked set (local + server)
    const unlockedIds = new Set(currentAchievements.map(a => `${a.badgeId}-${a.substance}`));
    const newUnlocked: Achievement[] = [];
    let badgeToCelebrate: BadgeDefinition | null = null;

    for (const badge of BADGE_DEFINITIONS) {
      for (const substance of ['nicotine', 'weed'] as const) {
        const key = `${badge.id}-${substance}`;
        if (unlockedIds.has(key)) continue;

        const isEligible = checkBadgeEligibility(badge.id, usage, prefs, substance);
        if (isEligible) {
          try {
            const result = await unlockAchievement(badge.id, substance);
            if (result.isNew && result.achievement) {
              newUnlocked.push(result.achievement);
              // Prioritize celebrating the first one found
              if (!badgeToCelebrate) {
                badgeToCelebrate = badge;
              }
            }
          } catch (e) {
            console.error('Error unlocking achievement:', e);
          }
        }
      }
    }

    if (newUnlocked.length > 0) {
      // Update local state with ALL new achievements
      setAchievements(prev => [...prev, ...newUnlocked]);

      // Show celebration for determining badge
      if (badgeToCelebrate) {
        setNewBadge(badgeToCelebrate);
        setShowCelebration(true);
      }
    }

    return newUnlocked.length > 0;
  }, []);

  useEffect(() => {
    const init = async () => {
      const { prefs, usage, achvs } = await loadData();

      if (!prefs.hasCompletedSetup) {
        setShowSetup(true);
      } else {
        // Check for achievements
        await checkAndUnlockAchievements(usage, prefs, achvs);

        // Check if running as PWA (home screen shortcut)
        // No longer automatically showing substance picker
        if (shouldShowUsagePrompt()) {
          markPromptShown();
        }
      }

      setIsLoading(false);
    };

    init();
  }, [loadData, checkAndUnlockAchievements]);

  const handleSetupComplete = async (data: { substance: 'nicotine' | 'weed'; name: string; age: number; religion: 'christian' | 'secular' }) => {
    const today = getTodayString();
    const newPrefs: UserPreferences = {
      substance: data.substance,
      trackingStartDate: today,
      hasCompletedSetup: true,
      dailyGoal: null,
      quitPlan: null,
      userName: data.name,
      userAge: data.age,
      religion: data.religion,
    };
    await savePreferencesAsync(newPrefs);
    setPreferences(newPrefs);
    setShowSetup(false);
    setIsSubstancePickerOpen(true);
    setRefreshKey(prev => prev + 1);
  };

  const handleUsageSubmit = async (count: number, substance: 'nicotine' | 'weed') => {
    if (!preferences) {
      setIsSubstancePickerOpen(false);
      setActiveLoggingSubstance(null);
      return;
    }

    let latestPrefs = preferences;

    if (count > 0) {
      const today = getTodayString();
      const now = new Date().toISOString();

      await saveUsageEntryAsync({
        date: today,
        count,
        substance,
      });

      // Update preferences with last usage time
      latestPrefs = {
        ...preferences,
        [substance === 'nicotine' ? 'lastNicotineUsageTime' : 'lastWeedUsageTime']: now,
      };

      // Force specific fields to be present to avoid partial update issues
      // This ensures that even if preferences is stale, we explicitly set the usage time
      const payload: UserPreferences = {
        ...latestPrefs,
        lastNicotineUsageTime: substance === 'nicotine' ? now : (latestPrefs.lastNicotineUsageTime ?? null),
        lastWeedUsageTime: substance === 'weed' ? now : (latestPrefs.lastWeedUsageTime ?? null),
      };

      await savePreferencesAsync(payload);
      setPreferences(payload);
    }

    setActiveLoggingSubstance(null);
    setIsSubstancePickerOpen(false);
    // Reload data and force calendar refresh
    const usage = await fetchUsageData();
    setUsageData(usage);
    setRefreshKey(prev => prev + 1);

    // Check for new achievements metrics FIRST
    await checkAndUnlockAchievements(usage, latestPrefs, achievements);

    // Force a fresh fetch of all data to ensure UI sync
    const freshAchievements = await fetchAchievements();
    setAchievements(freshAchievements);

    // THEN refresh UI components
    setRefreshKey(prev => prev + 1);
  };

  const handleGeneratePlan = async (targetSubstance: 'nicotine' | 'weed') => {
    if (!preferences) return;

    const plan = generateQuitPlan(targetSubstance);

    // Construct new state
    const currentQuitState = preferences.quitState || {
      nicotine: { plan: null, startDate: null },
      weed: { plan: null, startDate: null }
    };

    const updatedQuitState = {
      ...currentQuitState,
      [targetSubstance]: {
        plan,
        startDate: currentQuitState[targetSubstance].startDate || (preferences.substance === targetSubstance ? preferences.trackingStartDate : null) || getTodayString()
      }
    };

    const updatedPrefs = {
      ...preferences,
      quitState: updatedQuitState
    };

    await savePreferencesAsync(updatedPrefs);
    setPreferences(updatedPrefs);
    setRefreshKey(prev => prev + 1);
  };

  const handleSavingsConfigChange = async (config: SavingsConfig) => {
    setSavingsConfig(config);
    await saveSavingsConfig(config);
  };

  const handleCelebrationComplete = () => {
    setShowCelebration(false);
    setNewBadge(null);
  };

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



  return (
    <div className="min-h-screen">
      <UserHeader
        user={user}
        preferences={preferences}
        onModalStateChange={handleModalStateChange}
      />

      <main className="container mx-auto px-4 py-4 sm:py-8 pb-4 sm:pb-8 max-w-full">
        {preferences && (
          <>
            {/* Floating Log Button - Simplified to toggle Picker */}
            <div className={`fixed bottom-6 right-6 z-40 transition-all duration-300 ${isModalOpen ? 'opacity-0 scale-90 pointer-events-none' : 'opacity-100 scale-100'} sm:block`}>
              <Button
                size="lg"
                onClick={() => setIsSubstancePickerOpen(!isSubstancePickerOpen)}
                className={`h-14 px-6 sm:h-16 sm:px-8 text-base sm:text-lg rounded-full shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 flex items-center gap-2 ${isSubstancePickerOpen
                  ? 'bg-white/10 text-white backdrop-blur-xl border border-white/20'
                  : 'bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary/70 text-white border-none'
                  }`}
              >
                {isSubstancePickerOpen ? (
                  <>
                    <X className="h-5 w-5 sm:h-6 sm:w-6" />
                    Cancel
                  </>
                ) : (
                  <>
                    <PlusCircle className="h-5 w-5 sm:h-6 sm:w-6" />
                    Log Usage
                  </>
                )}
              </Button>
            </div>

            {/* Dashboard Sections */}
            <div className="space-y-6 sm:space-y-12 relative overflow-hidden">
              {/* Mobile Navigation Buttons - LARGE */}
              <div className="sm:hidden">
                {currentPage > 0 && !isNavHidden && (
                  <button
                    onClick={() => scrollToPage(currentPage - 1)}
                    className="fixed left-3 top-[55%] -translate-y-1/2 z-40 p-5 rounded-full glass border border-white/20 shadow-2xl active:scale-90 transition-all duration-300 group"
                    style={{
                      background: theme === 'light' ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.6)',
                      backdropFilter: 'blur(16px)',
                      boxShadow: '0 8px 32px rgba(0,0,0,0.2)'
                    }}
                  >
                    <ChevronLeft className="h-8 w-8 text-primary group-hover:scale-110" />
                  </button>
                )}
                {currentPage < 3 && !isNavHidden && (
                  <button
                    onClick={() => scrollToPage(currentPage + 1)}
                    className="fixed right-3 top-[55%] -translate-y-1/2 z-40 p-5 rounded-full glass border border-white/20 shadow-2xl active:scale-90 transition-all duration-300 group"
                    style={{
                      background: theme === 'light' ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.6)',
                      backdropFilter: 'blur(16px)',
                      boxShadow: '0 8px 32px rgba(0,0,0,0.2)'
                    }}
                  >
                    <ChevronRight className="h-8 w-8 text-primary group-hover:scale-110" />
                  </button>
                )}
              </div>

              {/* DESKTOP LAYOUT - Hidden on mobile */}
              <div className="hidden sm:block space-y-8">
                {/* Row 1: Mood + Quit Plan */}
                <div className="grid grid-cols-2 gap-6">
                  <MoodTracker />
                  <UnifiedQuitPlanCard
                    preferences={preferences}
                    usageData={usageData}
                    onGeneratePlan={handleGeneratePlan}
                    refreshKey={refreshKey}
                  />
                </div>

                {/* Row 2: Calendar/Quote */}
                <div id="calendar-section">
                  <UsageCalendar
                    key={refreshKey}
                    usageData={usageData}
                    onDataUpdate={loadData}
                    userId={user.id}
                    religion={preferences.religion}
                    onReligionUpdate={async (religion: 'christian' | 'secular') => {
                      const updatedPrefs = { ...preferences, religion };
                      setPreferences(updatedPrefs);
                      await savePreferencesAsync(updatedPrefs);
                    }}
                    preferences={preferences}
                    onPreferencesUpdate={async (updatedPrefs: UserPreferences) => {
                      await savePreferencesAsync(updatedPrefs);
                      setPreferences(updatedPrefs);
                    }}
                  />
                </div>

                {/* Row 3: Achievements + Health Recovery */}
                <div className="grid grid-cols-2 gap-6">
                  <AchievementsCard
                    key={`achievements-${refreshKey}`}
                    achievements={achievements}
                    substance={preferences.substance}
                  />
                  <HealthTimelineCard
                    key={`health-${refreshKey}`}
                    usageData={usageData}
                    preferences={preferences}
                  />
                </div>

                {/* Row 4: Savings + Stats */}
                <div className="grid grid-cols-2 gap-6">
                  <SavingsTrackerCard
                    key={`savings-${refreshKey}`}
                    savingsConfig={savingsConfig}
                    usageData={usageData}
                    trackingStartDate={preferences.trackingStartDate}
                    onSavingsConfigChange={handleSavingsConfigChange}
                    onModalStateChange={handleModalStateChange}
                  />
                  <div className="grid grid-cols-2 gap-4">
                    <StatsCard key={`stats-nicotine-${refreshKey}`} usageData={usageData} substance="nicotine" />
                    <StatsCard key={`stats-weed-${refreshKey}`} usageData={usageData} substance="weed" />
                  </div>
                </div>
              </div>

              {/* MOBILE SWIPE LAYOUT - Hidden on desktop */}
              <div
                ref={swipeContainerRef}
                onScroll={handleScroll}
                className="swipe-container sm:hidden"
              >

                {/* SLIDE 1: Mindset (Mood & Personalized Plan) */}
                <div className="swipe-item space-y-4">
                  <div className="flex items-center justify-between mb-2 px-1">
                    <h2 className="text-[10px] font-bold uppercase tracking-[0.2em] opacity-50">Daily Mindset</h2>
                  </div>
                  <div className="space-y-4">
                    <MoodTracker />
                    <UnifiedQuitPlanCard
                      preferences={preferences}
                      usageData={usageData}
                      onGeneratePlan={handleGeneratePlan}
                      refreshKey={refreshKey}
                    />
                  </div>
                </div>

                {/* SLIDE 2: Stats & Recovery (Side-by-side Stats + Health) */}
                <div className="swipe-item space-y-4">
                  <div className="flex items-center justify-between mb-2 px-1">
                    <h2 className="text-[10px] font-bold uppercase tracking-[0.2em] opacity-50">Usage & Recovery</h2>
                  </div>
                  <div className="space-y-4">
                    <div className="grid grid-cols-2 gap-3">
                      <StatsCard key={`stats-nicotine-${refreshKey}`} usageData={usageData} substance="nicotine" />
                      <StatsCard key={`stats-weed-${refreshKey}`} usageData={usageData} substance="weed" />
                    </div>
                    <HealthTimelineCard
                      key={`health-${refreshKey}`}
                      usageData={usageData}
                      preferences={preferences}
                    />
                  </div>
                </div>

                {/* SLIDE 3: Achievements & Money (Insights) */}
                <div className="swipe-item space-y-4">
                  <div className="flex items-center justify-between mb-2 px-1">
                    <h2 className="text-[10px] font-bold uppercase tracking-[0.2em] opacity-50">Achievements & Savings</h2>
                  </div>
                  <div className="space-y-4">
                    <AchievementsCard
                      key={`achievements-${refreshKey}`}
                      achievements={achievements}
                      substance={preferences.substance}
                    />
                    <SavingsTrackerCard
                      key={`savings-${refreshKey}`}
                      savingsConfig={savingsConfig}
                      usageData={usageData}
                      trackingStartDate={preferences.trackingStartDate}
                      onSavingsConfigChange={handleSavingsConfigChange}
                      onModalStateChange={handleModalStateChange}
                    />
                  </div>
                </div>

                {/* SLIDE 4: Calendar */}
                <div id="calendar-section-mobile" className="swipe-item">
                  <div className="flex items-center justify-between mb-2 px-1">
                    <h2 className="text-[10px] font-bold uppercase tracking-[0.2em] opacity-50">Usage Calendar</h2>
                  </div>
                  <UsageCalendar
                    key={refreshKey}
                    usageData={usageData}
                    onDataUpdate={loadData}
                    userId={user.id}
                    religion={preferences.religion}
                    onReligionUpdate={async (religion: 'christian' | 'secular') => {
                      const updatedPrefs = { ...preferences, religion };
                      setPreferences(updatedPrefs);
                      await savePreferencesAsync(updatedPrefs);
                    }}
                    preferences={preferences}
                    onPreferencesUpdate={async (updatedPrefs: UserPreferences) => {
                      await savePreferencesAsync(updatedPrefs);
                      setPreferences(updatedPrefs);
                    }}
                  />
                </div>

              </div>
            </div>
          </>
        )}
      </main>

      <SetupWizard open={showSetup} onComplete={handleSetupComplete} />

      <UsageLoggerDropUp
        isOpen={isSubstancePickerOpen}
        onSelect={(substance) => {
          setActiveLoggingSubstance(substance);
          setIsSubstancePickerOpen(false);
        }}
        onClose={() => setIsSubstancePickerOpen(false)}
      />

      {activeLoggingSubstance && (
        <ScrollWheelLogger
          substance={activeLoggingSubstance}
          onSubmit={handleUsageSubmit}
          onCancel={() => setActiveLoggingSubstance(null)}
        />
      )}

      <VersionUpdateModal />

      {showCelebration && newBadge && (
        <CelebrationAnimation
          badge={newBadge}
          onComplete={handleCelebrationComplete}
        />
      )}
    </div>
  );
}
