'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { useLanguage } from '@/context/LanguageContext';

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

export default function PromoHome() {
  const { t } = useLanguage();
  const router = useRouter();
  const [promos, setPromos] = useState<Promo[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
        const [promosRes, featuredRes] = await Promise.all([
          fetch(`${apiUrl}/api/promos`),
          fetch(`${apiUrl}/api/promos/featured`)
        ]);

        if (promosRes.ok) {
          const data = await promosRes.json();
          setPromos(data);
        }
      } catch (error) {
        console.error('Error fetching promos:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const featuredPromos = promos.filter(p => p.featured && p.isActive);
  const otherPromos = promos.filter(p => !p.featured && p.isActive);

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

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

  const handleBannerClick = (slug: string) => {
    router.push(`/promo/${slug}`);
  };

  if (loading) {
    return (
      <section className="py-16 md:py-20 bg-white">
        <div className="container-custom text-center">
          <p className="text-grey-dark">Memuat promo...</p>
        </div>
      </section>
    );
  }

  return (
    <section className="py-16 md:py-20 bg-white">
      <div className="container-custom">
        {/* Banner Utama - Featured Promo */}
        {featuredPromos.length > 0 && (
          <Link href={`/promo/${featuredPromos[0].slug || featuredPromos[0].title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')}`} className="block">
            <div className="relative rounded-xl overflow-hidden shadow-lg mb-12">
              {featuredPromos[0].image ? (
                <Image
                  src={featuredPromos[0].image}
                  alt={featuredPromos[0].title}
                  width={1200}
                  height={400}
                  className="w-full h-auto object-cover"
                />
              ) : (
                <div className="w-full h-40 bg-gradient-to-r from-gold/30 to-blush/30 flex items-center justify-center">
                  <span className="text-6xl">🎁</span>
                </div>
              )}
              <div className="absolute inset-0 bg-gradient-to-r from-espresso/90 via-espresso/50 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">
                    {t('promo.title')}
                  </span>
                  <h2 className="font-cormorant text-3xl md:text-4xl font-bold text-white mb-2">
                    {featuredPromos[0].title}
                  </h2>
                  <p className="text-ivory/80 text-sm md:text-base mb-4 line-clamp-2">
                    {stripHtml(featuredPromos[0].description)}
                  </p>
                  <p className="text-gold text-sm font-semibold mb-4">
                    ⏰ Periode: {formatDateRange(featuredPromos[0].periodStart, featuredPromos[0].periodEnd)}
                  </p>
                  <div className="flex flex-wrap gap-3">
                    <Link href="/online-booking" className="inline-block px-6 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark hover:text-white transition">
                      Booking Sekarang
                    </Link>
                    <a href="https://api.whatsapp.com/send/?phone=6281911111636&text&type=phone_number&app_absent=0" target="_blank" rel="noopener noreferrer" className="inline-block px-6 py-3 border border-white text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-white hover:text-espresso transition">
                      Booking via WhatsApp
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </Link>
        )}

        {/* Promo Cards */}
        <div className="text-center mb-10">
          <h2 className="font-cormorant text-3xl md:text-5xl text-espresso font-bold mb-4">{t('promo.title')}</h2>
          <div className="w-12 h-0.5 bg-gold mx-auto mb-4"></div>
          <p className="text-grey-dark">{t('promo.subtitle')}</p>
        </div>

        <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
          {otherPromos.slice(0, 4).map((promo) => {
            const promoSlug = promo.slug || promo.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
            const categoryIcon = promo.category === 'special' ? '🎁' : promo.category === 'monthly' ? '📅' : promo.category === 'package' ? '💳' : '🆕';

            return (
              <Link key={promo.id} href={`/promo/${promoSlug}`} className="group">
                <div className="relative overflow-hidden rounded-lg border border-blush bg-white hover:outline hover:outline-2 hover:outline-gold transition-all duration-300">
                  <div className="h-40 bg-blush flex items-center justify-center text-5xl group-hover:scale-110 transition-transform duration-500">
                    {promo.image ? (
                      <Image src={promo.image} alt={promo.title} fill className="object-cover" />
                    ) : (
                      categoryIcon
                    )}
                  </div>
                  <div className="p-4 md:p-5">
                    <h3 className="font-cormorant text-xl font-semibold text-espresso mb-1">{promo.title}</h3>
                    <p className="text-xs text-grey-dark mb-3 line-clamp-2">{stripHtml(promo.description)}</p>
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-semibold text-gold">{promo.promoPrice}</span>
                      <span className="text-xs text-espresso group-hover:translate-x-1 transition-transform">Lihat →</span>
                    </div>
                  </div>
                </div>
              </Link>
            );
          })}
        </div>

        <div className="text-center mt-10">
          <Link href="/promo" className="inline-block px-8 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded hover:bg-gold-dark hover:text-white transition duration-300">
            {t('promo.see-all')}
          </Link>
        </div>
      </div>
    </section>
  );
}
