'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useParams } from 'next/navigation';
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 | string;
  name: string;
  slug?: string;
}

export default function PromoDetailPage() {
  const params = useParams();
  const slugOrId = params.slug as string;
  const { t } = useLanguage();

  const [promo, setPromo] = useState<Promo | null>(null);
  const [categories, setCategories] = useState<PromoCategory[]>(localCategories);
  const [allPromos, setAllPromos] = useState<Promo[]>(localPromos);
  const [loading, setLoading] = useState(true);

  // Fetch promos from backend
  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();
          setAllPromos(data);

          // Find promo by slug or auto-generated slug
          const found = data.find((p: any) => {
            const promoSlug = p.slug || p.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
            return promoSlug === slugOrId;
          });
          setPromo(found || null);
        }

        if (catsRes.ok) {
          const data = await catsRes.json();
          setCategories(data);
        }
      } catch (error) {
        console.error('Error fetching promo:', error);
        // Try to find from local data as fallback
        const found = localPromos.find((p) => {
          const pSlug = p.slug || p.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
          return pSlug === slugOrId;
        });
        setPromo(found || null);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [slugOrId]);

  const formatDateRange = (start: string | null | undefined, end: string | null | undefined) => {
    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 category = categories.find((c) => c.slug === promo?.category);
  const otherPromos = allPromos.filter((p) => p.id !== promo?.id).slice(0, 3);

  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 details...</p>
        </div>
        <Footer />
      </main>
    );
  }

  if (!promo) {
    return (
      <main className="min-h-screen bg-ivory">
        <Navbar />
        <div className="container-custom text-center py-24">
          <p className="text-5xl mb-4">🚀</p>
          <h1 className="font-cormorant text-3xl font-bold text-espresso mb-4">Promo tidak ditemukan</h1>
          <Link href="/promo" className="text-gold hover:underline font-semibold">&larr; Kembali ke Promo</Link>
        </div>
        <Footer />
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-ivory">
      <Navbar />

      {/* Breadcrumb */}
      <section className="relative py-16 md:py-24 bg-espresso overflow-hidden">
        <div className="container-custom text-center text-white relative z-10">
          <nav className="mb-4 text-xs tracking-widest uppercase text-white">
            <Link href="/" className="hover:text-gold transition text-white">Home</Link>
            <span className="mx-2 text-white">/</span>
            <Link href="/promo" className="hover:text-gold transition text-white">Promo</Link>
            <span className="mx-2 text-white">/</span>
            <span className="text-white/60">{promo.title}</span>
          </nav>
          <h1 className="font-cormorant text-4xl md:text-6xl font-bold mb-4 uppercase text-white">{promo.title}</h1>
          <p className="text-ivory/80 max-w-2xl mx-auto text-lg">{stripHtml(promo.description)}</p>
        </div>
      </section>

      {/* Banner Image - only if promo has image field */}
      {promo.image && (
        <section className="-mt-12 relative z-10">
          <div className="container-custom">
            <Image src={promo.image} alt={promo.title} width={1200} height={400} className="w-full rounded-xl object-cover shadow-lg" />
          </div>
        </section>
      )}

      {/* Content */}
      <section className="py-16">
        <div className="container-custom max-w-4xl">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Main */}
            <div className="lg:col-span-2 space-y-6">
              <div className="bg-white rounded-xl border border-blush p-8 text-center">
                <span className="inline-block px-4 py-1.5 bg-blush text-gold text-xs font-bold rounded-full mb-4">{category?.name || promo.category}</span>
                <h2 className="font-cormorant text-3xl font-bold text-espresso mb-4">{promo.title}</h2>
                <div className="text-grey-dark mb-6 max-w-lg mx-auto prose prose-sm" dangerouslySetInnerHTML={{ __html: promo.description }} />
                <div className="bg-ivory rounded-xl p-6 max-w-sm mx-auto">
                  {promo.normalPrice && (
                    <p className="text-sm text-grey line-through mb-1">{promo.normalPrice}</p>
                  )}
                  <div className="flex items-center justify-center gap-3">
                    <span className="text-3xl md:text-4xl font-bold text-gold">{promo.promoPrice}</span>
                    {promo.discount && (
                      <span className="text-sm bg-red-500 text-white px-3 py-1 rounded-full font-bold">-{promo.discount}</span>
                    )}
                  </div>
                </div>
                <div className="mt-6 flex flex-col sm:flex-row gap-3 justify-center">
                  <Link href="/online-booking" className="px-8 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark hover:text-white transition">{promo.cta || '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="px-8 py-3 border border-gold text-gold text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold hover:text-white transition">Booking via WhatsApp</a>
                </div>
              </div>

              <div className="bg-white rounded-xl border border-blush p-6">
                <h3 className="font-cormorant text-xl font-bold text-espresso mb-3">⏰ Periode Berlaku</h3>
                <p className="text-grey-dark">{formatDateRange(promo.periodStart, promo.periodEnd)}</p>
              </div>

              <div className="bg-gold rounded-xl p-6 text-white text-center">
                <p className="text-2xl mb-2">💬</p>
                <h3 className="font-cormorant text-xl font-bold mb-2">Ada yang ingin ditanyakan?</h3>
                <p className="text-white/80 text-sm mb-4">Hubungi tim customer care kami untuk informasi lebih lanjut</p>
                <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 bg-white text-espresso text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-ivory transition">Chat WhatsApp</a>
              </div>
            </div>

            {/* Sidebar */}
            <aside className="lg:col-span-1">
              <div className="sticky top-24 space-y-6">
                <div className="bg-white rounded-xl border border-blush p-6">
                  <h3 className="font-cormorant text-lg font-bold text-espresso mb-4">📋 Syarat & Ketentuan</h3>
                  <ul className="space-y-2 text-sm text-grey-dark">
                    <li>• Promo tidak dapat digabungkan dengan promo/voucher lain</li>
                    <li>• Promo berlaku selama persediaan masih ada</li>
                    <li>• Reservasi wajib dilakukan minimal 1 hari sebelumnya</li>
                    <li>• Pembatalan maksimal 3 jam sebelum jadwal</li>
                    <li>• Harga spesial berlaku untuk pembayaran tunai/debit</li>
                  </ul>
                </div>

                <div className="bg-white rounded-xl border border-blush p-6">
                  <h3 className="font-cormorant text-lg font-bold text-espresso mb-4">🕐 Jam Operasional</h3>
                  <div className="space-y-1 text-sm text-grey-dark">
                    <p>Senin - Jumat: 10:00 - 21:00</p>
                    <p>Sabtu: 10:00 - 22:00</p>
                    <p>Minggu: 10:00 - 21:00</p>
                  </div>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </section>

      {/* Other Promos */}
      {otherPromos.length > 0 && (
        <section className="bg-white py-16">
          <div className="container-custom">
            <h2 className="font-cormorant text-2xl md:text-3xl font-bold text-espresso text-center mb-10">Promo Lainnya</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {otherPromos.map((p) => {
                const otherSlug = p.slug || p.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
                return (
                <Link key={p.id} href={`/promo/${otherSlug}`} className="group bg-ivory rounded-xl border border-blush p-6 hover:shadow-lg transition text-center">
                  <div className="text-4xl mb-3">{p.icon || '🎁'}</div>
                  <span className="inline-block px-3 py-1 bg-gold/10 text-gold text-xs font-bold rounded-full mb-3">{categories.find(c => c.slug === p.category)?.name || p.category}</span>
                  <h3 className="font-cormorant text-lg font-bold text-espresso mb-2 group-hover:text-gold transition">{p.title}</h3>
                  <p className="text-xs text-grey-dark mb-3 line-clamp-2">{stripHtml(p.description)}</p>
                  <div className="text-gold font-bold">{p.promoPrice}</div>
                  {p.discount && <span className="text-xs text-red-500 font-bold">-{p.discount}</span>}
                </Link>
                );
              })}
            </div>
          </div>
        </section>
      )}

      <Footer />
    </main>
  );
}
