'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { promos as localPromos, promoCategories as localCategories } from '@/data/promos';
import { useLanguage } from '@/context/LanguageContext';

interface Promo {
  id?: number | string;
  slug?: string;
  title: string;
  description: string;
  normalPrice: string;
  promoPrice: string;
  discount: string;
  periodStart?: string | null;
  periodEnd?: string | null;
  period?: string;
  category: string;
  featured?: boolean;
  isActive?: boolean;
  icon?: string;
  cta?: string;
  image?: string;
}

interface PromoCategory {
  id?: number;
  name: string;
  slug: string;
}

export default function PromoPage() {
  const [selectedCategory, setSelectedCategory] = useState('');
  const [promos, setPromos] = useState<Promo[]>(localPromos as any);
  const [categories, setCategories] = useState<PromoCategory[]>(localCategories as any);
  const [loading, setLoading] = useState(true);
  const { t } = useLanguage();

  // Fetch promos from backend on mount
  useEffect(() => {
    const fetchData = async () => {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
        const [promosRes, catsRes] = await Promise.all([
          fetch(`${apiUrl}/api/promos`),
          fetch(`${apiUrl}/api/promo-categories`)
        ]);

        if (promosRes.ok) {
          const data = await promosRes.json();
          // Map backend promo data to frontend format
          const mappedPromos = data.map((p: any) => ({
            ...p,
            icon: p.category === 'special' ? '🎁' : p.category === 'monthly' ? '📅' : p.category === 'package' ? '💳' : '🆕',
            cta: 'Booking Sekarang',
            slug: p.slug || p.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')
          }));
          setPromos(mappedPromos);
        }

        if (catsRes.ok) {
          const data = await catsRes.json();
          setCategories(data);
        }
      } catch (error) {
        console.error('Error fetching promos:', error);
        // Keep local data as fallback
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const formatDateRange = (start: string | null, end: string | null) => {
    if (!start || !end) return '';
    const startDate = new Date(start);
    const endDate = new Date(end);
    const startDay = startDate.getDate();
    const endDay = endDate.getDate();
    const endMonth = endDate.toLocaleString('id-ID', { month: 'long' });
    const endYear = endDate.getFullYear();
    return `${startDay} - ${endDay} ${endMonth} ${endYear}`;
  };

  // Strip HTML tags for plain text display
  const stripHtml = (html: string | null) => (html || '').replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim();

  const filteredPromos = !selectedCategory
    ? promos
    : promos.filter((promo) => promo.category === selectedCategory);

  const featuredPromos = promos.filter((p) => p.featured);
  const [activeFeatured, setActiveFeatured] = useState(0);

  const prevFeature = () => setActiveFeatured((prev) => (prev === 0 ? featuredPromos.length - 1 : prev - 1));
  const nextFeature = () => setActiveFeatured((prev) => (prev + 1) % featuredPromos.length);

  if (loading) {
    return (
      <main className="min-h-screen bg-ivory">
        <Navbar />
        <div className="container-custom py-24 text-center">
          <p className="text-grey-dark">Loading promo data...</p>
        </div>
        <Footer />
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-ivory">
      <Navbar />
      <section className="relative py-16 md:py-24 bg-espresso overflow-hidden">
        <div className="container-custom text-center text-white relative z-10">
          <h1 className="font-cormorant text-4xl md:text-6xl font-bold mb-4 uppercase text-white">{t('promo.page.title')}</h1>
          <p className="text-ivory/80 max-w-2xl mx-auto">{t('promo.page.subtitle')}</p>
          <nav className="mt-4 text-xs tracking-widest uppercase text-white">
            <Link href="/" className="hover:text-gold transition text-white">{t('breadcrumb.home')}</Link>
            <span className="mx-2 text-white">/</span>
            <span className="text-white/60">{t('breadcrumb.promo')}</span>
          </nav>
        </div>
      </section>

      {/* Featured Promo Slider */}
      {featuredPromos.length > 0 && (
        <section className="py-12">
          <div className="container-custom">
            <div className="relative rounded-xl overflow-hidden shadow-lg">
              {(() => {
                const featuredSlug = featuredPromos[activeFeatured].slug ||
                  featuredPromos[activeFeatured].title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
                return (
                  <>
                    <Link href={`/promo/${featuredSlug}`}>
                      <Image
                        src={featuredPromos[activeFeatured].image || '/images/promo/dine-at-hyatt.jpeg'}
                        alt={featuredPromos[activeFeatured].title}
                        width={1200}
                        height={500}
                        className="w-full h-auto object-cover"
                      />
                      <div className="absolute inset-0 bg-gradient-to-r from-espresso/80 via-espresso/40 to-transparent flex items-center">
                        <div className="p-8 md:p-12 max-w-lg">
                          <span className="inline-block px-3 py-1 bg-gold text-white text-xs font-bold rounded-full mb-4">🔥 PROMO BULAN INI</span>
                          <h2 className="font-cormorant text-3xl md:text-5xl font-bold text-white mb-3">{featuredPromos[activeFeatured].title}</h2>
                          <p className="text-ivory/80 text-sm md:text-base mb-2" dangerouslySetInnerHTML={{ __html: featuredPromos[activeFeatured].description }} />
                          <p className="text-gold font-semibold text-sm mb-6">⏰ {featuredPromos[activeFeatured].period}</p>
                          <span className="inline-block px-6 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark transition">Lihat Detail</span>
                        </div>
                      </div>
                    </Link>

                    {featuredPromos.length > 1 && (
                      <>
                        <button onClick={prevFeature} className="absolute left-4 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center text-white hover:bg-white/40 transition">
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7"/></svg>
                        </button>
                        <button onClick={nextFeature} className="absolute right-4 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center text-white hover:bg-white/40 transition">
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7"/></svg>
                        </button>
                        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-10 flex gap-2">
                          {featuredPromos.map((_, i) => (
                            <button key={i} onClick={() => setActiveFeatured(i)} className={`w-2.5 h-2.5 rounded-full transition-all ${i === activeFeatured ? 'bg-gold w-6' : 'bg-white/50 hover:bg-white/80'}`} />
                          ))}
                        </div>
                      </>
                    )}
                  </>
                );
              })()}
            </div>
          </div>
        </section>
      )}

      {/* Filter */}
      <section className="sticky top-16 z-40 bg-ivory border-b border-blush py-4">
        <div className="container-custom">
          <div className="flex flex-wrap gap-2">
            <button onClick={() => setSelectedCategory('')} className={`px-4 py-2 rounded-full text-xs uppercase tracking-wider font-semibold transition ${!selectedCategory ? 'bg-gold text-white' : 'border border-gold text-gold hover:bg-gold hover:text-white'}`}>{t('promo.filter.all')}</button>
            {categories.map((cat) => (
              <button key={cat.slug} onClick={() => setSelectedCategory(cat.slug)} className={`px-4 py-2 rounded-full text-xs uppercase tracking-wider font-semibold transition ${selectedCategory === cat.slug ? 'bg-gold text-white' : 'border border-gold text-gold hover:bg-gold hover:text-white'}`}>{cat.name}</button>
            ))}
          </div>
        </div>
      </section>

      {/* Promo Cards */}
      <section className="py-12">
        <div className="container-custom">
          {filteredPromos.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredPromos.map((promo) => {
                const promoSlug = promo.slug || promo.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
                return (
                  <Link key={promo.id} href={`/promo/${promoSlug}`} className="bg-white rounded-xl overflow-hidden hover:shadow-lg transition-all duration-300 border border-blush group block">
                    {promo.image && (
                      <div className="relative h-44 bg-gradient-to-br from-gold/20 to-gold/5 flex items-center justify-center overflow-hidden">
                        <Image src={promo.image} alt={promo.title} fill className="object-cover group-hover:scale-110 transition-transform duration-500" />
                        {promo.discount && (
                          <span className="absolute top-3 right-3 bg-red-500 text-white text-xs font-bold px-2.5 py-1 rounded-full">-{promo.discount}</span>
                        )}
                      </div>
                    )}
                    <div className="p-5">
                      <h3 className="font-cormorant text-xl font-bold text-espresso mb-2">{promo.title}</h3>
                      <p className="text-sm text-grey-dark mb-3 line-clamp-2">{stripHtml(promo.description)}</p>
                      {promo.normalPrice && promo.promoPrice && (
                        <div className="bg-ivory rounded-lg p-3 mb-3">
                          <div className="flex justify-between items-center mb-1">
                            <span className="text-xs text-grey line-through">{promo.normalPrice}</span>
                          </div>
                          <div className="text-xl font-bold text-gold">{promo.promoPrice}</div>
                        </div>
                      )}
                      <p className="text-xs text-grey mb-4">⏰ {t('promo.period')}: {formatDateRange(promo.periodStart || null, promo.periodEnd || null)}</p>
                      <span className="inline-block text-xs text-gold font-semibold group-hover:translate-x-1 transition">Lihat Detail →</span>
                    </div>
                  </Link>
                );
              })}
            </div>
          ) : (
            <div className="text-center py-12"><p className="text-grey-dark">{t('general.no-results')}</p></div>
          )}
        </div>
      </section>

      {/* Terms */}
      <section className="bg-white py-12">
        <div className="container-custom">
          <h2 className="font-cormorant text-2xl font-bold text-espresso mb-6">📋 {t('promo.terms')}</h2>
          <div className="space-y-3 text-grey-dark max-w-2xl">
            {[1,2,3,4,5,6,7].map(i => <p key={i}>{i}. {t(`promo.terms.${i}`)}</p>)}
          </div>
        </div>
      </section>
      <Footer />
    </main>
  );
}
