'use client';

import { useState, useMemo } from 'react';
import { Sparkles, Settings, BookOpen, Quote as QuoteIcon, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { savePreferencesAsync, getPreferences, UserPreferences } from '@/lib/storage';

type Religion = 'christian' | 'secular';

interface Verse {
    text: string;
    source: string;
}

const VERSES: Record<Religion, Verse[]> = {
    christian: [
        { text: "I can do all things through Christ which strengtheneth me.", source: "Philippians 4:13 (KJV)" },
        { text: "For God hath not given us the spirit of fear; but of power, and of love, and of a sound mind.", source: "2 Timothy 1:7 (KJV)" },
        { text: "But they that wait upon the LORD shall renew their strength; they shall mount up with wings as eagles.", source: "Isaiah 40:31 (KJV)" },
        { text: "Be strong and of a good courage; be not afraid, neither be thou dismayed: for the LORD thy God is with thee whithersoever thou goest.", source: "Joshua 1:9 (KJV)" },
        { text: "The LORD is my shepherd; I shall not want.", source: "Psalm 23:1 (KJV)" },
        { text: "Trust in the LORD with all thine heart; and lean not unto thine own understanding.", source: "Proverbs 3:5 (KJV)" },
        { text: "And be not conformed to this world: but be ye transformed by the renewing of your mind.", source: "Romans 12:2 (KJV)" },
        { text: "Cast thy burden upon the LORD, and he shall sustain thee.", source: "Psalm 55:22 (KJV)" },
        { text: "Fear thou not; for I am with thee: be not dismayed; for I am thy God: I will strengthen thee.", source: "Isaiah 41:10 (KJV)" },
        { text: "Come unto me, all ye that labour and are heavy laden, and I will give you rest.", source: "Matthew 11:28 (KJV)" },
        { text: "The name of the LORD is a strong tower: the righteous runneth into it, and is safe.", source: "Proverbs 18:10 (KJV)" },
        { text: "Peace I leave with you, my peace I give unto you: not as the world giveth, give I unto you.", source: "John 14:27 (KJV)" },
        { text: "If God be for us, who can be against us?", source: "Romans 8:31 (KJV)" },
        { text: "He healeth the broken in heart, and bindeth up their wounds.", source: "Psalm 147:3 (KJV)" },
        { text: "Wait on the LORD: be of good courage, and he shall strengthen thine heart.", source: "Psalm 27:14 (KJV)" },
        { text: "My flesh and my heart faileth: but God is the strength of my heart, and my portion for ever.", source: "Psalm 73:26 (KJV)" },
        { text: "God is our refuge and strength, a very present help in trouble.", source: "Psalm 46:1 (KJV)" },
        { text: "In him was life; and the life was the light of men.", source: "John 1:4 (KJV)" },
        { text: "Therefore if any man be in Christ, he is a new creature: old things are passed away; behold, all things are become new.", source: "2 Corinthians 5:17 (KJV)" },
        { text: "The LORD shall fight for you, and ye shall hold your peace.", source: "Exodus 14:14 (KJV)" },
    ],
    secular: [
        { text: "The only way to do great work is to love what you do.", source: "Steve Jobs" },
        { text: "It is during our darkest moments that we must focus to see the light.", source: "Aristotle" },
        { text: "The greatest glory in living lies not in never falling, but in rising every time we fall.", source: "Nelson Mandela" },
        { text: "In the middle of difficulty lies opportunity.", source: "Albert Einstein" },
        { text: "What you get by achieving your goals is not as important as what you become by achieving your goals.", source: "Zig Ziglar" },
        { text: "The future belongs to those who believe in the beauty of their dreams.", source: "Eleanor Roosevelt" },
        { text: "It does not matter how slowly you go as long as you do not stop.", source: "Confucius" },
        { text: "Everything you've ever wanted is on the other side of fear.", source: "George Addair" },
        { text: "The best time to plant a tree was 20 years ago. The second best time is now.", source: "Chinese Proverb" },
        { text: "You are never too old to set another goal or to dream a new dream.", source: "C.S. Lewis" },
        { text: "The only impossible journey is the one you never begin.", source: "Tony Robbins" },
        { text: "Success is not final, failure is not fatal: it is the courage to continue that counts.", source: "Winston Churchill" },
        { text: "Believe you can and you're halfway there.", source: "Theodore Roosevelt" },
        { text: "The pain you feel today will be the strength you feel tomorrow.", source: "Arnold Schwarzenegger" },
        { text: "Your life does not get better by chance, it gets better by change.", source: "Jim Rohn" },
        { text: "The secret of change is to focus all of your energy not on fighting the old, but on building the new.", source: "Socrates" },
        { text: "What lies behind us and what lies before us are tiny matters compared to what lies within us.", source: "Ralph Waldo Emerson" },
        { text: "The man who moves a mountain begins by carrying away small stones.", source: "Confucius" },
        { text: "Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.", source: "Thomas Edison" },
        { text: "Fall seven times, stand up eight.", source: "Japanese Proverb" },
    ]
};

interface DailyInspirationCardProps {
    initialReligion?: Religion | null;
    onReligionChange?: (religion: Religion) => void;
}

export function DailyInspirationCard({ initialReligion, onReligionChange }: DailyInspirationCardProps) {
    const [currentReligion, setCurrentReligion] = useState<Religion>(initialReligion || 'secular');

    // Get a quote based on the day of the year and selected religion
    const dailyVerse = useMemo(() => {
        const verses = VERSES[currentReligion];
        const now = new Date();
        const start = new Date(now.getFullYear(), 0, 0);
        const diff = now.getTime() - start.getTime();
        const oneDay = 1000 * 60 * 60 * 24;
        const dayOfYear = Math.floor(diff / oneDay);
        return verses[dayOfYear % verses.length];
    }, [currentReligion]);

    const handleReligionChange = async (religion: Religion) => {
        setCurrentReligion(religion);

        // Save to backend if we can
        const prefs = getPreferences();
        if (prefs) {
            const updatedPrefs: UserPreferences = {
                ...prefs,
                religion: religion
            };
            await savePreferencesAsync(updatedPrefs);
        }

        if (onReligionChange) {
            onReligionChange(religion);
        }
    };

    const getLabel = (r: Religion) => {
        switch (r) {
            case 'christian': return 'Christian (KJV)';
            case 'secular': return 'Secular (Quotes)';
        }
    };

    const getIcon = () => {
        if (currentReligion === 'christian') {
            return <BookOpen className="h-4 w-4 text-yellow-300 animate-pulse-subtle" />;
        }
        return <Sparkles className="h-4 w-4 text-yellow-300 animate-pulse-subtle" />;
    };

    const getBackground = () => {
        if (currentReligion === 'christian') {
            return 'linear-gradient(135deg, rgba(59, 130, 246, 0.35) 0%, rgba(37, 99, 235, 0.3) 50%, rgba(30, 64, 175, 0.4) 100%)'; // Blue
        }
        return 'linear-gradient(135deg, rgba(67, 56, 202, 0.35) 0%, rgba(109, 40, 217, 0.3) 50%, rgba(76, 29, 149, 0.4) 100%)'; // Indigo/Original
    };

    const getShadowColor = () => {
        if (currentReligion === 'christian') {
            return 'rgba(59, 130, 246, 0.15)';
        }
        return 'rgba(99, 102, 241, 0.15)';
    };

    return (
        <div
            className="flex-1 flex flex-col justify-center p-5 rounded-xl border border-white/10 min-h-[120px] relative overflow-hidden group"
            style={{
                background: getBackground(),
                boxShadow: `inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 4px 20px ${getShadowColor()}`
            }}
        >
            <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-white/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2" />

            <div className="relative z-10">
                <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-2">
                        {getIcon()}
                        <span className="text-xs font-semibold text-white/80 uppercase tracking-wider">
                            {currentReligion === 'secular' ? 'Daily Inspiration' : 'Daily Verse'}
                        </span>
                    </div>

                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button
                                variant="ghost"
                                size="icon"
                                className="h-6 w-6 text-white/50 hover:text-white hover:bg-white/10 rounded-full"
                            >
                                <Settings className="h-3.5 w-3.5" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                            {(['christian', 'secular'] as Religion[]).map((r) => (
                                <DropdownMenuItem
                                    key={r}
                                    onClick={() => handleReligionChange(r)}
                                    className="flex items-center justify-between gap-2"
                                >
                                    <span>{getLabel(r)}</span>
                                    {currentReligion === r && <Check className="h-4 w-4" />}
                                </DropdownMenuItem>
                            ))}
                        </DropdownMenuContent>
                    </DropdownMenu>
                </div>

                <p className="text-sm font-medium text-white leading-relaxed mb-3 text-shadow-sm italic">
                    &ldquo;{dailyVerse.text}&rdquo;
                </p>
                <p className="text-xs text-white/70 font-medium">
                    — {dailyVerse.source}
                </p>
            </div>
        </div>
    );
}
