'use client';

import { useState, useCallback, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, Cake, Gift, Star, Heart, Loader2, Sparkles,
  Calendar, ThumbsUp, ThumbsDown, Target, Sun
} from 'lucide-react';

interface DailyBrief {
  sign: string;
  emoji: string;
  dates: string;
  dailyAdvice: string;
  luckyNumber: number;
  mood: string;
  focusArea: string;
  compatibility: string;
  doToday: string;
  avoidToday: string;
}

const BIRTHDAY_FREEBIES = [
  { company: 'Starbucks', offer: 'Free birthday drink (any size, any drink)', how: 'Join Starbucks Rewards 30+ days before your birthday', icon: '\u2615' },
  { company: 'Denny\u2019s', offer: 'Free Grand Slam breakfast', how: 'Show ID on your birthday', icon: '\ud83e\udd5e' },
  { company: 'Sephora', offer: 'Free birthday gift set', how: 'Join Beauty Insider (free)', icon: '\ud83d\udc84' },
  { company: 'Ulta Beauty', offer: 'Free birthday gift + 2x points', how: 'Join Ultamate Rewards', icon: '\u2728' },
  { company: 'Krispy Kreme', offer: 'Free dozen original glazed', how: 'Join Rewards app', icon: '\ud83c\udf69' },
  { company: 'Baskin-Robbins', offer: 'Free scoop of ice cream', how: 'Join Birthday Club online', icon: '\ud83c\udf68' },
  { company: 'IHOP', offer: 'Free stack of pancakes', how: 'Join MyHOP email list', icon: '\ud83e\udd5e' },
  { company: 'Red Robin', offer: 'Free birthday burger', how: 'Join Red Robin Royalty', icon: '\ud83c\udf54' },
  { company: 'Panera Bread', offer: 'Free pastry or sweet', how: 'Join MyPanera rewards', icon: '\ud83c\udf5e' },
  { company: 'Firehouse Subs', offer: 'Free medium sub', how: 'Join Firehouse Rewards', icon: '\ud83e\udd6a' },
  { company: 'Nothing Bundt Cakes', offer: 'Free bundtlet', how: 'Join eClub', icon: '\ud83c\udf82' },
  { company: 'Moe\u2019s Southwest Grill', offer: 'Free burrito', how: 'Join Moe Rewards', icon: '\ud83c\udf2f' },
];

const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];

export default function BirthdayBriefPage() {
  const [month, setMonth] = useState(0);
  const [day, setDay] = useState(0);
  const [brief, setBrief] = useState<DailyBrief | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showFreebies, setShowFreebies] = useState(false);

  const handleSubmit = useCallback(async () => {
    if (!month || !day) { setError('Please select your birthday month and day.'); return; }
    setLoading(true); setError(''); setBrief(null);
    try {
      const res = await fetch('/api/demos/birthday-brief', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ month, day }),
      });
      const data = await res.json();
      if (data.error) throw new Error(data.error);
      setBrief(data);
      setShowFreebies(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to generate brief.');
    } finally {
      setLoading(false);
    }
  }, [month, day]);

  const focusIcon = (area: string) => {
    switch (area) {
      case 'career': return <Target className="w-4 h-4" />;
      case 'relationships': return <Heart className="w-4 h-4" />;
      case 'health': return <Sun className="w-4 h-4" />;
      case 'creativity': return <Sparkles className="w-4 h-4" />;
      case 'finances': return <Gift className="w-4 h-4" />;
      default: return <Star className="w-4 h-4" />;
    }
  };

  return (
    <main className="min-h-screen bg-[#0C1222]">
      <div className="max-w-4xl mx-auto px-6 py-8">
        <Link href="/demos" className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-300 text-sm mb-8 transition-colors">
          <ArrowLeft className="w-4 h-4" /> Back to Demos
        </Link>

        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="mb-8">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-center">
              <Cake className="w-5 h-5 text-amber-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">BirthdayBrief</h1>
              <p className="text-gray-500 text-sm">Free birthday promos + daily no-BS astrology advice</p>
            </div>
          </div>
        </motion.div>

        {/* Birthday Input */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}>
          <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6 mb-6">
            <h2 className="text-sm font-semibold text-white mb-4 flex items-center gap-2"><Calendar className="w-4 h-4 text-amber-400" /> Your Birthday</h2>
            <div className="flex flex-wrap gap-4 items-end">
              <div>
                <label className="text-xs text-gray-400 mb-1 block">Month</label>
                <select value={month} onChange={e => setMonth(parseInt(e.target.value))} className="bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-amber-500 focus:outline-none">
                  <option value={0} className="bg-gray-900">Select month</option>
                  {MONTHS.map((m, i) => <option key={m} value={i + 1} className="bg-gray-900">{m}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-gray-400 mb-1 block">Day</label>
                <select value={day} onChange={e => setDay(parseInt(e.target.value))} className="bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-amber-500 focus:outline-none">
                  <option value={0} className="bg-gray-900">Day</option>
                  {Array.from({ length: 31 }, (_, i) => <option key={i + 1} value={i + 1} className="bg-gray-900">{i + 1}</option>)}
                </select>
              </div>
              <button onClick={handleSubmit} disabled={loading || !month || !day} className="flex items-center gap-2 px-6 py-2 rounded-xl bg-gradient-to-r from-amber-500/80 to-orange-500/80 hover:from-amber-500 hover:to-orange-500 text-white font-medium text-sm disabled:opacity-40 disabled:cursor-not-allowed transition-all">
                {loading ? <><Loader2 className="w-4 h-4 animate-spin" /> Loading...</> : <><Sparkles className="w-4 h-4" /> Get My Brief</>}
              </button>
            </div>
            {error && <p className="text-red-400 text-sm mt-3">{error}</p>}
          </div>
        </motion.div>

        {/* Brief Results */}
        <AnimatePresence>
          {brief && (
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="space-y-6">
              {/* Sign Card */}
              <div className="bg-gradient-to-br from-amber-500/5 to-orange-500/5 border border-amber-500/20 rounded-xl p-6 text-center">
                <span className="text-5xl">{brief.emoji}</span>
                <h3 className="text-2xl font-bold text-white mt-2">{brief.sign}</h3>
                <p className="text-gray-500 text-sm">{brief.dates}</p>
              </div>

              {/* Daily Advice */}
              <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                <h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
                  <Sun className="w-4 h-4 text-amber-400" /> Today\u2019s Advice \u2014 No Mystical BS
                </h3>
                <p className="text-gray-300 text-sm leading-relaxed">{brief.dailyAdvice}</p>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-4">
                  <div className="bg-black/20 rounded-lg px-3 py-2 text-center">
                    <p className="text-[10px] text-gray-500 uppercase">Mood</p>
                    <p className="text-sm text-white font-medium capitalize">{brief.mood}</p>
                  </div>
                  <div className="bg-black/20 rounded-lg px-3 py-2 text-center">
                    <p className="text-[10px] text-gray-500 uppercase">Focus</p>
                    <p className="text-sm text-white font-medium capitalize flex items-center justify-center gap-1">{focusIcon(brief.focusArea)} {brief.focusArea}</p>
                  </div>
                  <div className="bg-black/20 rounded-lg px-3 py-2 text-center">
                    <p className="text-[10px] text-gray-500 uppercase">Lucky #</p>
                    <p className="text-sm text-amber-400 font-bold">{brief.luckyNumber}</p>
                  </div>
                  <div className="bg-black/20 rounded-lg px-3 py-2 text-center">
                    <p className="text-[10px] text-gray-500 uppercase">Best Match Today</p>
                    <p className="text-xs text-gray-300">{brief.compatibility}</p>
                  </div>
                </div>
                <div className="grid md:grid-cols-2 gap-3 mt-4">
                  <div className="flex items-start gap-3 bg-emerald-500/5 border border-emerald-500/10 rounded-lg px-4 py-3">
                    <ThumbsUp className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
                    <div><p className="text-[10px] text-emerald-400 uppercase mb-0.5">Do Today</p><p className="text-xs text-gray-300">{brief.doToday}</p></div>
                  </div>
                  <div className="flex items-start gap-3 bg-red-500/5 border border-red-500/10 rounded-lg px-4 py-3">
                    <ThumbsDown className="w-4 h-4 text-red-400 shrink-0 mt-0.5" />
                    <div><p className="text-[10px] text-red-400 uppercase mb-0.5">Skip Today</p><p className="text-xs text-gray-300">{brief.avoidToday}</p></div>
                  </div>
                </div>
              </div>

              {/* Birthday Freebies */}
              {showFreebies && (
                <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                  <h3 className="text-sm font-semibold text-white mb-4 flex items-center gap-2">
                    <Gift className="w-4 h-4 text-pink-400" /> Birthday Freebies \u2014 {BIRTHDAY_FREEBIES.length} Deals
                  </h3>
                  <div className="grid md:grid-cols-2 gap-3">
                    {BIRTHDAY_FREEBIES.map((freebie) => (
                      <div key={freebie.company} className="flex items-start gap-3 bg-black/20 rounded-lg px-4 py-3">
                        <span className="text-xl">{freebie.icon}</span>
                        <div>
                          <p className="text-sm text-white font-medium">{freebie.company}</p>
                          <p className="text-xs text-emerald-400">{freebie.offer}</p>
                          <p className="text-[10px] text-gray-500 mt-0.5">{freebie.how}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>

        <div className="text-center mt-12 text-gray-700 text-xs">
          Built by The Hearth \u2022 <Link href="/demos" className="text-sky-500/50 hover:text-sky-400">View all demos</Link>
        </div>
      </div>
    </main>
  );
}
