'use client';

import { useState, useEffect, useMemo } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Smile, Meh, Frown, TrendingUp, ChevronLeft, ChevronRight, MessageSquare, Quote, Sparkles } from 'lucide-react';
import { MoodEntry, fetchMoodEntries, saveMoodEntry } from '@/lib/storage';
import { ResponsiveContainer, BarChart, Bar, XAxis, Tooltip, Cell } from 'recharts';
import { format, subDays, startOfWeek, endOfWeek, eachDayOfInterval } from 'date-fns';
import { cn } from '@/lib/utils';

import { useTheme } from '@/lib/theme-context';

export function MoodTracker() {
    const { theme } = useTheme();
    const [entries, setEntries] = useState<MoodEntry[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [affirmation, setAffirmation] = useState<string | null>(null);
    const [weekOffset, setWeekOffset] = useState(0);
    const [activeMood, setActiveMood] = useState<'good' | 'neutral' | 'bad' | null>(null);
    const [currentTimeout, setCurrentTimeout] = useState<NodeJS.Timeout | null>(null);

    useEffect(() => {
        const loadMoods = async () => {
            const data = await fetchMoodEntries();
            setEntries(data);
            if (data.length > 0) {
                // If the most recent entry is today, set it as active
                const today = format(new Date(), 'yyyy-MM-dd');
                const lastEntry = data[0];
                if (lastEntry.date === today) {
                    setActiveMood(lastEntry.mood as any);
                }
            }
            setIsLoading(false);
        };
        loadMoods();
    }, []);

    const handleMoodSelect = async (mood: 'good' | 'neutral' | 'bad') => {
        setIsSaving(true);
        setAffirmation(null);
        setActiveMood(mood);

        if (currentTimeout) {
            clearTimeout(currentTimeout);
            setCurrentTimeout(null);
        }

        try {
            const result = await saveMoodEntry(mood);
            if (result) {
                setEntries(prev => {
                    // Remove existing entry for today if it exists to avoid duplicates in state
                    const filtered = prev.filter(e => e.date !== result.entry.date);
                    return [result.entry, ...filtered];
                });
                setAffirmation(result.affirmation);

                const timeout = setTimeout(() => {
                    setAffirmation(null);
                    setCurrentTimeout(null);
                }, 8000);
                setCurrentTimeout(timeout);
            }
        } finally {
            setIsSaving(false);
        }
    };

    const weeklyData = useMemo(() => {
        const today = new Date();
        const start = startOfWeek(subDays(today, weekOffset * 7), { weekStartsOn: 1 });
        const end = endOfWeek(start, { weekStartsOn: 1 });
        const days = eachDayOfInterval({ start, end });

        return days.map(day => {
            const dateStr = format(day, 'yyyy-MM-dd');
            // Find the *latest* entry for this day
            const dayEntry = entries.find(e => e.date === dateStr);

            // Map mood to numeric values: bad=1, neutral=2, good=3
            let value = 0;
            if (dayEntry) {
                if (dayEntry.mood === 'good') value = 3;
                else if (dayEntry.mood === 'neutral') value = 2;
                else if (dayEntry.mood === 'bad') value = 1;
            }

            return {
                name: format(day, 'EEE'),
                fullDate: dateStr,
                value: value === 0 ? 0.2 : value, // 0.2 provides a small placeholder bar
                isPlaceholder: value === 0,
                mood: dayEntry?.mood
            };
        });
    }, [entries, weekOffset]);

    const weekLabel = useMemo(() => {
        const start = startOfWeek(subDays(new Date(), weekOffset * 7), { weekStartsOn: 1 });
        const end = endOfWeek(start, { weekStartsOn: 1 });
        if (weekOffset === 0) return 'This Week';
        if (weekOffset === 1) return 'Last Week';
        return `${format(start, 'MMM d')} - ${format(end, 'MMM d')}`;
    }, [weekOffset]);

    const getGradient = () => {
        if (theme === 'light') {
            switch (activeMood) {
                case 'good':
                    return 'from-emerald-100 via-teal-50 to-emerald-100 border-emerald-200 shadow-emerald-500/5';
                case 'neutral':
                    return 'from-amber-100 via-orange-50 to-amber-100 border-amber-200 shadow-amber-500/5';
                case 'bad':
                    return 'from-rose-100 via-red-50 to-rose-100 border-rose-200 shadow-rose-500/5';
                default:
                    return 'from-indigo-50 via-white to-indigo-50 border-indigo-100 shadow-indigo-500/5';
            }
        }

        switch (activeMood) {
            case 'good':
                return 'from-emerald-500/10 via-teal-500/5 to-emerald-500/10 border-emerald-500/20 shadow-emerald-500/10';
            case 'neutral':
                return 'from-amber-500/10 via-orange-500/5 to-amber-500/10 border-amber-500/20 shadow-amber-500/10';
            case 'bad':
                return 'from-rose-500/10 via-red-500/5 to-rose-500/10 border-rose-500/20 shadow-rose-500/10';
            default:
                return 'from-violet-500/10 via-indigo-500/5 to-violet-500/10 border-white/10 shadow-indigo-500/5';
        }
    };

    return (
        <Card className={cn(
            "overflow-hidden transition-all duration-700 backdrop-blur-xl border shadow-xl",
            "bg-gradient-to-br",
            getGradient()
        )}>
            <CardHeader className="pb-4">
                <div className="flex items-center justify-between">
                    <CardTitle className={cn(
                        "text-base sm:text-lg font-medium flex items-center gap-2",
                        theme === 'light' ? "text-slate-700" : "text-white/90"
                    )}>
                        <div className={cn("p-1.5 rounded-lg transition-colors duration-500",
                            activeMood === 'good' ? (theme === 'light' ? "bg-emerald-100 text-emerald-600" : "bg-emerald-500/20 text-emerald-400") :
                                activeMood === 'neutral' ? (theme === 'light' ? "bg-amber-100 text-amber-600" : "bg-amber-500/20 text-amber-400") :
                                    activeMood === 'bad' ? (theme === 'light' ? "bg-rose-100 text-rose-600" : "bg-rose-500/20 text-rose-400") :
                                        (theme === 'light' ? "bg-indigo-100 text-indigo-500" : "bg-white/10 text-white/70")
                        )}>
                            <Sparkles className="w-4 h-4" />
                        </div>
                        How are you feeling?
                    </CardTitle>

                    <div className={cn(
                        "flex items-center gap-1 rounded-full p-0.5 border",
                        theme === 'light'
                            ? "bg-slate-100 border-slate-200"
                            : "bg-black/20 border-white/5"
                    )}>
                        <Button
                            variant="ghost"
                            size="icon"
                            className={cn(
                                "h-6 w-6 rounded-full",
                                theme === 'light'
                                    ? "text-slate-400 hover:text-slate-700 hover:bg-white"
                                    : "text-white/50 hover:text-white hover:bg-white/10"
                            )}
                            onClick={() => setWeekOffset(prev => prev + 1)}
                        >
                            <ChevronLeft className="w-3 h-3" />
                        </Button>
                        <span className={cn(
                            "text-[10px] font-medium px-2 uppercase tracking-wider min-w-[60px] text-center",
                            theme === 'light' ? "text-slate-500" : "text-white/60"
                        )}>
                            {weekLabel}
                        </span>
                        <Button
                            variant="ghost"
                            size="icon"
                            className={cn(
                                "h-6 w-6 rounded-full disabled:opacity-20",
                                theme === 'light'
                                    ? "text-slate-400 hover:text-slate-700 hover:bg-white"
                                    : "text-white/50 hover:text-white hover:bg-white/10"
                            )}
                            disabled={weekOffset === 0}
                            onClick={() => setWeekOffset(prev => prev - 1)}
                        >
                            <ChevronRight className="w-3 h-3" />
                        </Button>
                    </div>
                </div>
            </CardHeader>

            <CardContent className="pt-2 space-y-4">
                {/* Mood Selection */}
                <div className="grid grid-cols-3 gap-3">
                    {[
                        { id: 'good', icon: Smile, label: 'Good', color: 'emerald' },
                        { id: 'neutral', icon: Meh, label: 'Okay', color: 'amber' },
                        { id: 'bad', icon: Frown, label: 'Bad', color: 'rose' }
                    ].map((item) => {
                        const isSelected = activeMood === item.id;
                        const Icon = item.icon;

                        return (
                            <button
                                key={item.id}
                                onClick={() => handleMoodSelect(item.id as any)}
                                disabled={isSaving}
                                className={cn(
                                    "group relative flex flex-col items-center justify-center gap-2 p-3 rounded-2xl transition-all duration-300",
                                    "border",
                                    isSelected
                                        ? (theme === 'light'
                                            ? `bg-${item.color}-100 border-${item.color}-200 shadow-sm`
                                            : `bg-${item.color}-500/20 border-${item.color}-500/50 shadow-[0_0_20px_-5px_var(--color-${item.color}-500)]`)
                                        : (theme === 'light'
                                            ? "bg-white border-slate-200 hover:bg-slate-50 hover:border-slate-300 hover:-translate-y-1 shadow-sm"
                                            : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20 hover:-translate-y-1")
                                )}
                            >
                                <div className={cn(
                                    "p-2 rounded-xl transition-all duration-300",
                                    isSelected
                                        ? `bg-${item.color}-500 text-white shadow-lg scale-110`
                                        : (theme === 'light'
                                            ? `bg-slate-100 text-slate-400 group-hover:text-${item.color}-500 group-hover:scale-110`
                                            : `bg-white/5 text-white/60 group-hover:text-${item.color}-400 group-hover:scale-110`)
                                )}>
                                    <Icon className={cn("w-5 h-5", isSelected && "animate-pulse-subtle")} />
                                </div>
                                <span className={cn(
                                    "text-[10px] font-semibold tracking-wide uppercase transition-colors",
                                    isSelected
                                        ? (theme === 'light' ? `text-${item.color}-700` : "text-white")
                                        : (theme === 'light' ? "text-slate-400 group-hover:text-slate-600" : "text-white/40 group-hover:text-white/80")
                                )}>
                                    {item.label}
                                </span>
                            </button>
                        );
                    })}
                </div>

                {/* Dynamic Affirmation */}
                <div className={cn(
                    "relative overflow-hidden transition-all duration-500 ease-out",
                    affirmation ? "opacity-100 max-h-24 translate-y-0" : "opacity-0 max-h-0 translate-y-4"
                )}>
                    <div className={cn(
                        "rounded-xl p-3 flex gap-3 items-center border",
                        theme === 'light'
                            ? "bg-indigo-50 border-indigo-100"
                            : "bg-gradient-to-r from-indigo-500/10 to-purple-500/10 border-indigo-500/20"
                    )}>
                        <div className={cn(
                            "p-1.5 rounded-full shrink-0",
                            theme === 'light' ? "bg-indigo-100 text-indigo-500" : "bg-indigo-500/20"
                        )}>
                            <Quote className={cn("w-3.5 h-3.5", theme === 'light' ? "text-indigo-500" : "text-indigo-400")} />
                        </div>
                        <p className={cn(
                            "text-xs font-medium leading-relaxed",
                            theme === 'light' ? "text-indigo-900" : "text-indigo-100/90"
                        )}>
                            {affirmation}
                        </p>
                    </div>
                </div>

                {/* Mini Graph */}
                <div className="space-y-3 pt-0">
                    <div className={cn(
                        "flex items-center gap-2 text-[10px] font-medium uppercase tracking-widest px-1",
                        theme === 'light' ? "text-slate-400" : "text-white/40"
                    )}>
                        <TrendingUp className="w-3 h-3" />
                        <span>Mood Tracking</span>
                    </div>

                    <div className={cn(
                        "h-28 w-full rounded-xl border p-2 relative group",
                        theme === 'light'
                            ? "bg-white/50 border-slate-200"
                            : "bg-white/5 border-white/5"
                    )}>
                        {/* Grid lines background effect */}
                        <div className={cn(
                            "absolute inset-0 bg-[size:14px_14px] pointer-events-none",
                            theme === 'light'
                                ? "bg-[linear-gradient(to_right,rgba(0,0,0,0.03)_1px,transparent_1px),linear-gradient(to_bottom,rgba(0,0,0,0.03)_1px,transparent_1px)] mask-image-linear-gradient(to_bottom,transparent,black)]"
                                : "bg-[linear-gradient(to_right,rgba(255,255,255,0.03)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.03)_1px,transparent_1px)] mask-image-linear-gradient(to_bottom,transparent,black)]"
                        )} />

                        <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={weeklyData} barSize={36}>
                                <Tooltip
                                    cursor={{ fill: theme === 'light' ? 'rgba(0,0,0,0.03)' : 'rgba(255,255,255,0.05)', radius: 4 }}
                                    content={({ active, payload }) => {
                                        if (active && payload && payload.length) {
                                            const data = payload[0].payload;
                                            if (data.isPlaceholder) return null;

                                            return (
                                                <div className={cn(
                                                    "p-2 rounded-lg shadow-xl backdrop-blur-md border",
                                                    theme === 'light'
                                                        ? "bg-white/95 border-slate-200 text-slate-900"
                                                        : "bg-slate-900/90 border-white/10 text-white"
                                                )}>
                                                    <p className={cn("text-xs font-medium mb-1", theme === 'light' ? "text-slate-600" : "text-white")}>{data.fullDate}</p>
                                                    <p className={cn(
                                                        "text-xs font-bold capitalize",
                                                        data.mood === 'good' ? (theme === 'light' ? "text-emerald-600" : "text-emerald-400") :
                                                            data.mood === 'neutral' ? (theme === 'light' ? "text-amber-600" : "text-amber-400") :
                                                                (theme === 'light' ? "text-rose-600" : "text-rose-400")
                                                    )}>
                                                        {data.mood}
                                                    </p>
                                                </div>
                                            );
                                        }
                                        return null;
                                    }}
                                />
                                <XAxis
                                    dataKey="name"
                                    axisLine={false}
                                    tickLine={false}
                                    tick={{ fill: theme === 'light' ? 'rgba(0,0,0,0.4)' : 'rgba(255,255,255,0.4)', fontSize: 10, dy: 10 }}
                                />
                                <Bar dataKey="value" radius={[4, 4, 4, 4]}>
                                    {weeklyData.map((entry, index) => {
                                        let fillColor;
                                        if (entry.isPlaceholder) {
                                            fillColor = theme === 'light' ? 'rgba(0,0,0,0.05)' : 'rgba(255,255,255,0.05)';
                                        } else if (entry.mood === 'good') {
                                            fillColor = theme === 'light' ? '#10b981' : '#34d399'; // emerald-500 : emerald-400
                                        } else if (entry.mood === 'neutral') {
                                            fillColor = theme === 'light' ? '#f59e0b' : '#fbbf24'; // amber-500 : amber-400
                                        } else {
                                            fillColor = theme === 'light' ? '#f43f5e' : '#fb7185'; // rose-500 : rose-400
                                        }

                                        return (
                                            <Cell
                                                key={`cell-${index}`}
                                                fill={fillColor}
                                                className="transition-all duration-300 hover:opacity-80"
                                            />
                                        );
                                    })}
                                </Bar>
                            </BarChart>
                        </ResponsiveContainer>
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}
