'use client';

import React, { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { blogPosts, blogCategories } from '@/data/blog';
import { useLanguage } from '@/context/LanguageContext';

interface BlogPost {
  id: string | number;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  category: string;
  author: string;
  date?: string;
  createdAt?: string;
  readTime?: number;
  image: string;
  tags?: string | null;
  metaTitle?: string | null;
  metaDesc?: string | null;
}

interface Category {
  id: string | number;
  name: string;
  slug?: string;
}

export default function BlogDetailPage() {
  const params = useParams();
  const slug = params.slug as string;
  const { t } = useLanguage();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [post, setPost] = useState<BlogPost | null>(null);
  const [recentList, setRecentList] = useState<BlogPost[]>([]);
  const [categories, setCategories] = useState<Category[]>(blogCategories as any);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const loadPost = async () => {
      try {
        setLoading(true);

        // Load categories (non-blocking)
        try {
          const catsRes = await fetch(`${apiUrl}/api/categories`);
          if (catsRes.ok) {
            const cats = await catsRes.json();
            if (Array.isArray(cats) && cats.length > 0) setCategories(cats);
          }
        } catch (e) { /* keep local categories */ }

        try {
          const response = await fetch(`${apiUrl}/api/articles/${slug}`);
          if (response.ok) {
            const data = await response.json();
            setPost(data);
            // Recent list from published articles
            try {
              const listRes = await fetch(`${apiUrl}/api/articles`);
              if (listRes.ok) {
                const list = await listRes.json();
                const recent = (Array.isArray(list) ? list : [])
                  .filter((p: any) => p.id !== data.id)
                  .slice(0, 5);
                setRecentList(recent);
              }
            } catch (e) { /* ignore */ }
            return;
          }
        } catch (apiError) {
          console.log('API not available, using local data');
        }

        const localPost = blogPosts.find((p) => p.slug === slug);
        if (localPost) {
          setPost(localPost as any);
          const recent = [...blogPosts]
            .filter((p) => p.id !== localPost.id)
            .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
            .slice(0, 5);
          setRecentList(recent as any);
        } else {
          setError('Artikel tidak ditemukan');
        }
      } catch (err) {
        setError('Gagal memuat artikel');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    if (slug) {
      loadPost();
    }
  }, [slug]);

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
  const shareUrl = `${siteUrl}/blog/${post?.slug || slug}`;
  const shareText = `${post?.title || ''} - ${shareUrl}`;

  if (loading) {
    return (
      <main className="min-h-screen bg-ivory">
        <Navbar />
        <div className="container-custom text-center py-24">
          <div className="text-5xl mb-4">⏳</div>
          <h1 className="font-cormorant text-3xl font-bold text-espresso mb-4">Memuat artikel...</h1>
        </div>
        <Footer />
      </main>
    );
  }

  if (error || !post) {
    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">{error || 'Artikel tidak ditemukan'}</h1>
          <Link href="/blog" className="text-gold hover:underline font-semibold">
            &larr; Kembali ke Blog
          </Link>
        </div>
        <Footer />
      </main>
    );
  }

  const catKey = (c: Category) => (c.slug || String(c.id));
  const category = categories.find((c) => catKey(c) === post.category);
  const postDate = post.date || post.createdAt || '';
  const isRealImage = !!post.image && (post.image.startsWith('/') || post.image.startsWith('http'));
  const imgSrc = post.image && post.image.startsWith('http') ? post.image : `${apiUrl}${post.image}`;
  const tagList = (post.tags || '').split(',').map(t => t.trim()).filter(Boolean);
  const recentIsReal = (img: string) => !!img && (img.startsWith('/') || img.startsWith('http'));

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

      {/* Breadcrumb */}
      <section className="relative py-12 md:py-16 bg-espresso">
        <div className="container-custom text-center text-white relative z-10">
          <h1 className="font-cormorant text-3xl md:text-5xl font-bold mb-4 text-white">{post.title}</h1>
          <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>
            <Link href="/blog" className="hover:text-gold transition text-white">{t('breadcrumb.blog')}</Link>
            <span className="mx-2 text-white">/</span>
            <span className="text-white/60">{category?.name || post.category}</span>
          </nav>
        </div>
      </section>

      {/* Article Content */}
      <section className="py-12 md:py-16">
        <div className="container-custom max-w-4xl">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Main Content */}
            <article className="lg:col-span-2">
              {/* Meta */}
              <div className="flex flex-wrap items-center gap-4 text-sm text-grey mb-6">
                <span className="px-3 py-1 bg-gold text-white text-xs font-bold rounded-full">
                  {category?.name || post.category}
                </span>
                <span>✍️ {post.author}</span>
                <span>📅 {postDate ? new Date(postDate).toLocaleDateString('id-ID') : ''}</span>
              </div>

              {/* Featured Image */}
              <div className="w-full h-64 md:h-80 bg-blush rounded-lg flex items-center justify-center text-7xl mb-8 overflow-hidden">
                {isRealImage
                  ? <img src={imgSrc} alt={post.title} className="w-full h-full object-cover" />
                  : (post.image || '✨')}
              </div>

              {/* Content (HTML from RichTextEditor) */}
              <div className="prose prose-lg max-w-none prose-headings:font-cormorant prose-headings:text-espresso prose-p:text-grey-dark prose-a:text-gold prose-img:rounded-lg" dangerouslySetInnerHTML={{ __html: post.content }} />

              {/* Tags */}
              {tagList.length > 0 && (
                <div className="mt-8 pt-6 border-t border-blush">
                  <div className="flex flex-wrap gap-2 items-center">
                    <span className="text-xs text-grey font-semibold">Tags:</span>
                    {tagList.map((tag, idx) => (
                      <span key={idx} className="px-3 py-1 bg-blush text-espresso text-xs rounded-full hover:bg-gold hover:text-white transition">
                        #{tag}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Share */}
              <div className="mt-6 pt-6 border-t border-blush">
                <p className="text-sm text-grey mb-3 font-semibold">{t('blog.share')}</p>
                <div className="flex gap-2 flex-wrap">
                  <a href={`https://wa.me/?text=${encodeURIComponent(shareText)}`} target="_blank" rel="noopener noreferrer"
                    className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                    <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.373-.273.299-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.884 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                  </a>
                  <a href={`https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(post.title)}`} target="_blank" rel="noopener noreferrer"
                    className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                    <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M11.944 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0a12 12 0 00-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 01.171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>
                  </a>
                  <a href={`https://www.instagram.com/`} target="_blank" rel="noopener noreferrer"
                    className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                    <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/></svg>
                  </a>
                  <a href={`https://facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`} target="_blank" rel="noopener noreferrer"
                    className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                    <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
                  </a>
                  <a href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}`} target="_blank" rel="noopener noreferrer"
                    className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                    <svg className="w-4 h-4 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
                  </a>
                  <a href={`mailto:?subject=${encodeURIComponent(post.title)}&body=${encodeURIComponent(shareText)}`} target="_blank" rel="noopener noreferrer"
                    className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                    <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                  </a>
                  <button onClick={() => { navigator.clipboard.writeText(shareUrl); alert('Link copied!'); }}
                    className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                    <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/></svg>
                  </button>
                </div>
              </div>

              {/* Author Box */}
              <div className="mt-8 p-6 bg-white rounded-lg border border-blush flex items-start gap-4">
                <div className="w-14 h-14 bg-gold rounded-full flex items-center justify-center text-white text-xl font-bold flex-shrink-0">
                  {post.author.charAt(0)}
                </div>
                <div>
                  <p className="font-semibold text-espresso">{post.author}</p>
                  <p className="text-sm text-grey-dark">{t('blog.author-desc')}</p>
                  <p className="text-sm text-grey-dark">Carla Skin Clinic</p>
                </div>
              </div>

              {/* Inline CTA */}
              <div className="mt-8 p-6 bg-gold rounded-lg text-center">
                <p className="text-white font-semibold mb-2">💡 {t('blog.cta-title')}</p>
                <p className="text-white/80 text-sm mb-4">{t('blog.cta-desc')}</p>
                <Link href="/online-booking" className="inline-block px-6 py-2 bg-white text-espresso text-xs uppercase tracking-widest font-semibold rounded hover:bg-ivory transition">
                  {t('blog.cta-btn')} →
                </Link>
              </div>
            </article>

            {/* Sidebar */}
            <aside className="lg:col-span-1">
              <div className="sticky top-24 space-y-6">
                {/* Recent Articles */}
                <div className="bg-white p-6 rounded-lg border border-blush">
                  <h3 className="font-cormorant text-lg font-bold text-espresso mb-4">{t('blog.recent')}</h3>
                  <div className="space-y-4">
                    {recentList.map((rp) => {
                      const rpDate = rp.date || rp.createdAt || '';
                      return (
                      <Link key={rp.id} href={`/blog/${rp.slug}`} className="block group">
                        <div className="flex gap-3">
                          <div className="w-12 h-12 bg-blush rounded flex items-center justify-center flex-shrink-0 text-xl overflow-hidden group-hover:scale-110 transition-transform">
                            {recentIsReal(rp.image)
                              ? <img src={rp.image.startsWith('http') ? rp.image : `${apiUrl}${rp.image}`} alt="" className="w-full h-full object-cover" />
                              : (rp.image || '✨')}
                          </div>
                          <div>
                            <p className="text-sm text-espresso font-semibold group-hover:text-gold transition line-clamp-2">
                              {rp.title}
                            </p>
                            <p className="text-xs text-grey mt-1">{rpDate ? new Date(rpDate).toLocaleDateString('id-ID') : ''}</p>
                          </div>
                        </div>
                      </Link>
                      );
                    })}
                  </div>
                </div>

                {/* Newsletter */}
                <div className="bg-gold p-6 rounded-lg text-white text-center">
                  <p className="text-2xl mb-2">📧</p>
                  <h3 className="font-cormorant text-lg font-bold mb-2">{t('blog.newsletter.title')}</h3>
                  <p className="text-sm text-white/80 mb-4">{t('blog.newsletter.desc')}</p>
                  <form onSubmit={(e) => { e.preventDefault(); alert('Terima kasih telah subscribe!'); }} className="space-y-2">
                    <input type="email" placeholder="Email Anda" className="w-full px-3 py-2 rounded text-espresso text-sm" required />
                    <button type="submit" className="w-full px-3 py-2 bg-espresso text-white text-xs uppercase tracking-widest font-semibold rounded hover:bg-espresso/80 transition">{t('blog.newsletter.btn')}</button>
                  </form>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </section>

      <Footer />
    </main>
  );
}
