'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useLanguage } from '@/context/LanguageContext';
import { eventsApi, contactsApi, Event } from '@/lib/api';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Input from '@/components/ui/Input';
import { 
  CalendarIcon, 
  MapPinIcon, 
  UserGroupIcon,
  ChatBubbleLeftRightIcon,
  AcademicCapIcon,
  SparklesIcon 
} from '@heroicons/react/24/outline';
import toast from 'react-hot-toast';

export default function HomePage() {
  const { t, locale } = useLanguage();
  const [nextEvent, setNextEvent] = useState<Event | null>(null);
  const [loading, setLoading] = useState(true);
  const [email, setEmail] = useState('');
  const [subscribing, setSubscribing] = useState(false);

  useEffect(() => {
    eventsApi.getNextUpcoming()
      .then(({ event }) => setNextEvent(event))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const handleSubscribe = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email) return;

    setSubscribing(true);
    try {
      await contactsApi.subscribe(email);
      toast.success(t('home.newsletter.success'));
      setEmail('');
    } catch (error) {
      toast.error(t('home.newsletter.error'));
    } finally {
      setSubscribing(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString(locale === 'es' ? 'es-ES' : 'en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  const formatTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleTimeString(locale === 'es' ? 'es-ES' : 'en-US', {
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <>
      {/* Hero Section */}
      <section className="bg-gradient-to-br from-white via-secondary-gray to-white">
        <div className="container-page py-16 md:py-24">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
            <div>
              <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold text-primary-dark leading-tight text-balance">
                {t('home.hero.title')}
              </h1>
              <p className="mt-6 text-xl text-gray-600">
                {t('home.hero.subtitle')}
              </p>
              <div className="mt-8 flex flex-wrap gap-4">
                <Link href="/events">
                  <Button size="lg">
                    {t('home.hero.cta')}
                  </Button>
                </Link>
                <Link href="/community">
                  <Button variant="outline" size="lg">
                    {t('common.learnMore')}
                  </Button>
                </Link>
              </div>
            </div>
            
            {/* Hero Image Grid */}
            <div className="relative">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-4">
                  <div className="relative rounded-card h-32 flex items-center justify-center overflow-hidden">
                    <Image
                      src="/images/2026-01-29 13.10.26.jpg"
                      alt="Language exchange event"
                      fill
                      sizes="(max-width: 1024px) 50vw, 25vw"
                      className="object-cover"
                    />
                    <div className="absolute inset-0 bg-primary-yellow/60" />
                    <ChatBubbleLeftRightIcon className="relative z-10 w-16 h-16 text-primary-dark opacity-50" />
                  </div>
                  <div className="relative rounded-card h-48 overflow-hidden">
                    <Image
                      src="/images/2026-01-29 13.10.23.jpg"
                      alt="Group language practice"
                      fill
                      sizes="(max-width: 1024px) 50vw, 25vw"
                      className="object-cover"
                    />
                  </div>
                </div>
                <div className="space-y-4 pt-8">
                  <div className="relative rounded-card h-48 overflow-hidden">
                    <Image
                      src="/images/2026-01-29 13.10.16.jpg"
                      alt="Community meetup"
                      fill
                      sizes="(max-width: 1024px) 50vw, 25vw"
                      className="object-cover"
                    />
                  </div>
                  <div className="relative rounded-card h-32 flex items-center justify-center overflow-hidden">
                    <Image
                      src="/images/2026-01-29 13.09.59.jpg"
                      alt="Language exchange group"
                      fill
                      sizes="(max-width: 1024px) 50vw, 25vw"
                      className="object-cover"
                    />
                    <div className="absolute inset-0 bg-secondary-brown/40" />
                    <UserGroupIcon className="relative z-10 w-16 h-16 text-secondary-brown opacity-70" />
                  </div>
                </div>
              </div>
              {/* Decorative elements */}
              <div className="absolute -top-4 -left-4 w-24 h-24 bg-primary-yellow/30 rounded-full blur-2xl" />
              <div className="absolute -bottom-4 -right-4 w-32 h-32 bg-secondary-blue/20 rounded-full blur-2xl" />
            </div>
          </div>
        </div>
      </section>

      {/* Next Event Section */}
      <section className="section-padding bg-white">
        <div className="container-page">
          <h2 className="section-title text-center">
            {t('home.nextEvent.title')}
          </h2>
          
          <div className="mt-12 max-w-3xl mx-auto">
            {loading ? (
              <div className="text-center py-12">
                <div className="animate-spin w-8 h-8 border-4 border-primary-yellow border-t-transparent rounded-full mx-auto" />
              </div>
            ) : nextEvent ? (
              <Link href={`/events/${nextEvent.id}`} className="block">
                <Card variant="elevated" className="p-8 cursor-pointer hover:shadow-lg transition-shadow">
                  <div className="flex flex-col md:flex-row gap-8">
                    <div className="flex-1">
                      <h3 className="text-2xl font-bold text-primary-dark">
                        {locale === 'es' && nextEvent.titleEs ? nextEvent.titleEs : nextEvent.title}
                      </h3>
                      <p className="mt-3 text-gray-600">
                        {locale === 'es' && nextEvent.descriptionEs 
                          ? nextEvent.descriptionEs 
                          : nextEvent.description}
                      </p>
                      
                      <div className="mt-6 space-y-3">
                        <div className="flex items-center gap-3 text-gray-700">
                          <CalendarIcon className="w-5 h-5 text-primary-yellow" />
                          <span>{formatDate(nextEvent.startDatetime)}</span>
                        </div>
                        <div className="flex items-center gap-3 text-gray-700">
                          <span className="w-5 h-5 flex items-center justify-center text-primary-yellow font-bold">
                            ⏰
                          </span>
                          <span>{formatTime(nextEvent.startDatetime)}</span>
                        </div>
                        <div className="flex items-center gap-3 text-gray-700">
                          <MapPinIcon className="w-5 h-5 text-primary-yellow" />
                          <span>{nextEvent.location}</span>
                        </div>
                      </div>
                    </div>
                    
                    <div className="flex flex-col justify-between items-start md:items-end">
                      <div className="text-right">
                        <span className="text-3xl font-bold text-primary-dark">
                          {nextEvent.price === 0 
                            ? t('events.details.free')
                            : `${nextEvent.price.toLocaleString()} ${nextEvent.currency}`}
                        </span>
                        <p className="text-sm text-gray-500 mt-1">
                          {nextEvent.availableSeats} {t('events.details.spotsLeft')}
                        </p>
                      </div>
                      <Button size="lg" className="mt-6">
                        {t('common.moreInfo')}
                      </Button>
                    </div>
                  </div>
                </Card>
              </Link>
            ) : (
              <div className="text-center py-12 text-gray-500">
                <CalendarIcon className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                <p className="text-lg">{t('home.nextEvent.noEvents')}</p>
                <p className="mt-2">{t('home.nextEvent.stayTuned')}</p>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* About Section */}
      <section className="section-padding bg-secondary-gray">
        <div className="container-page">
          <div className="text-center max-w-3xl mx-auto">
            <h2 className="section-title">{t('home.about.title')}</h2>
            <p className="section-subtitle">
              {t('home.about.description')}
            </p>
          </div>
          
          <div className="mt-16 grid grid-cols-1 md:grid-cols-3 gap-8">
            <Card className="p-8 text-center card-hover">
              <div className="w-16 h-16 mx-auto bg-primary-yellow/20 rounded-full flex items-center justify-center">
                <CalendarIcon className="w-8 h-8 text-primary-dark" />
              </div>
              <h3 className="mt-6 text-xl font-semibold">
                {t('home.about.feature1')}
              </h3>
              <p className="mt-3 text-gray-600">
                {t('home.about.feature1Desc')}
              </p>
            </Card>
            
            <Card className="p-8 text-center card-hover">
              <div className="w-16 h-16 mx-auto bg-primary-yellow/20 rounded-full flex items-center justify-center">
                <ChatBubbleLeftRightIcon className="w-8 h-8 text-primary-dark" />
              </div>
              <h3 className="mt-6 text-xl font-semibold">
                {t('home.about.feature2')}
              </h3>
              <p className="mt-3 text-gray-600">
                {t('home.about.feature2Desc')}
              </p>
            </Card>
            
            <Card className="p-8 text-center card-hover">
              <div className="w-16 h-16 mx-auto bg-primary-yellow/20 rounded-full flex items-center justify-center">
                <AcademicCapIcon className="w-8 h-8 text-primary-dark" />
              </div>
              <h3 className="mt-6 text-xl font-semibold">
                {t('home.about.feature3')}
              </h3>
              <p className="mt-3 text-gray-600">
                {t('home.about.feature3Desc')}
              </p>
            </Card>
          </div>
        </div>
      </section>

      {/* Newsletter Section */}
      <section className="section-padding bg-primary-dark text-white">
        <div className="container-page">
          <div className="max-w-2xl mx-auto text-center">
            <SparklesIcon className="w-12 h-12 mx-auto text-primary-yellow" />
            <h2 className="mt-6 text-3xl md:text-4xl font-bold">
              {t('home.newsletter.title')}
            </h2>
            <p className="mt-4 text-gray-300">
              {t('home.newsletter.description')}
            </p>
            
            <form onSubmit={handleSubscribe} className="mt-8 flex flex-col sm:flex-row gap-4 max-w-md mx-auto">
              <Input
                type="email"
                placeholder={t('home.newsletter.placeholder')}
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="flex-1 bg-white/10 border-white/20 text-white placeholder:text-gray-400"
                required
              />
              <Button type="submit" isLoading={subscribing}>
                {t('home.newsletter.button')}
              </Button>
            </form>
          </div>
        </div>
      </section>
    </>
  );
}
