import { trpc } from "@/lib/trpc";
import { useLocation } from "wouter";
import { useState, useEffect, useRef } from "react";
import { useHydrationTransition } from "@/hooks/useHydrationTransition";
import { Navbar } from '@/components/Navbar';
import { Footer } from "@/components/Footer";
import WorkshopCard from "@/components/WorkshopCard";
import { Heart, Clock, Users, Sparkles } from "lucide-react";
import { updateMetaTags, createStructuredData, createWorkshopsPageSchema } from '@/lib/seo';
import { useLanguage } from '@/contexts/LanguageContext';

// ─── Skeleton card ────────────────────────────────────────────────────────────
function WorkshopCardSkeleton() {
  return (
    <div className="rounded-2xl overflow-hidden border border-[#e8e8e8] bg-white shadow-sm">
      <div className="w-full aspect-[4/3] bg-gray-200 animate-pulse" />
      <div className="px-5 pt-5 pb-5 space-y-3">
        <div className="h-5 w-24 rounded-full bg-gray-200 animate-pulse" />
        <div className="h-6 w-3/4 rounded bg-gray-200 animate-pulse" />
        <div className="h-6 w-1/2 rounded bg-gray-200 animate-pulse" />
        <div className="h-4 w-full rounded bg-gray-100 animate-pulse" />
        <div className="h-4 w-5/6 rounded bg-gray-100 animate-pulse" />
        <div className="flex justify-between pt-3 border-t border-gray-100">
          <div className="h-8 w-16 rounded bg-gray-200 animate-pulse" />
          <div className="h-8 w-12 rounded bg-gray-200 animate-pulse" />
          <div className="h-8 w-14 rounded bg-gray-200 animate-pulse" />
        </div>
        <div className="h-10 w-full rounded-xl bg-gray-200 animate-pulse" />
      </div>
    </div>
  );
}

// ─── Animated card wrapper ────────────────────────────────────────────────────
function AnimatedCard({ children, index }: { children: React.ReactNode; index: number }) {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); observer.disconnect(); } },
      { threshold: 0.08 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  return (
    <div
      ref={ref}
      className="group relative"
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? 'translateY(0)' : 'translateY(28px)',
        transition: `opacity 0.45s ease ${index * 80}ms, transform 0.45s ease ${index * 80}ms`,
      }}
    >
      {children}
    </div>
  );
}

export default function Workshops() {
  const [, navigate] = useLocation();
  const { t, language } = useLanguage();
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [filterKey, setFilterKey] = useState(0);
  const [gridVisible, setGridVisible] = useState(true);
  const [heroVisible, setHeroVisible] = useState(false);

  const categories = [
    { id: 'all', label: t('workshops.allWorkshops') },
    { id: 'popular', label: t('workshops.popularWorkshops') },
    { id: 'couple', label: t('workshops.coupleWorkshops') },
    { id: 'group', label: t('workshops.groupWorkshops') },
  ];

  const STATS = [
    { icon: <Users className="w-4 h-4" />, num: '1 ' + (language === 'zh' ? '對' : 'pair'), label: language === 'zh' ? '每時段限額' : 'per session' },
    { icon: <Heart className="w-4 h-4" />, num: '50+', label: t('workshops.stats.couples') },
    { icon: <Clock className="w-4 h-4" />, num: '3–4h', label: language === 'zh' ? '沉浸式體驗' : 'immersive' },
    { icon: <Sparkles className="w-4 h-4" />, num: '100%', label: language === 'zh' ? '材料全包' : 'all-inclusive' },
  ];

  useEffect(() => {
    const timer = setTimeout(() => setHeroVisible(true), 60);
    return () => clearTimeout(timer);
  }, []);

  const dbCategory = selectedCategory === 'all' || selectedCategory === 'popular'
    ? undefined
    : selectedCategory;

  const { initialData } = useHydrationTransition();
  // SSR pre-populates workshops list — no loading state on first render
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const ssrWorkshops: any = (initialData?.page === "workshops" && !dbCategory)
    ? initialData.workshops ?? []
    : undefined;

  const workshopsQuery = trpc.workshops.list.useQuery({ category: dbCategory }, {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    initialData: ssrWorkshops,
    initialDataUpdatedAt: ssrWorkshops ? Date.now() - 30_000 : undefined,
    staleTime: 5 * 60 * 1000,
  });
  const origin = typeof window !== 'undefined' ? window.location.origin : '';

  // SEO: meta tags (language-aware)
  useEffect(() => {
    updateMetaTags({
      title: language === 'zh'
        ? '工作坊選擇 — Zoneout Studio 香港情侶手作工作坊'
        : 'Workshops — Zoneout Studio Hong Kong Couples Handcraft',
      description: language === 'zh'
        ? '香港拍拖好去處首選！探索 Zoneout Studio 全部情侶手作工作坊，包括 Tufting 地毯編織、純銀戒指訂製、流體藝術等私人包場體驗。每個時段僅接一對情侶，專業導師全程指導，材料全包。立即預約，創造屬於你們的獨家回憶！'
        : 'Best couple date idea in Hong Kong! Explore Zoneout Studio workshops — tufting rugs, silver rings, fluid art and more. Private sessions for couples only, expert instructor included, all materials provided. Book now and create your exclusive memory!',
      url: 'https://zoneout-workshop.com/workshops',
      type: 'website',
    });
  }, [language]);

  // SEO: dynamic CollectionPage schema
  useEffect(() => {
    if (!workshopsQuery.data?.length) return;
    const items = workshopsQuery.data.map((w: any) => ({
      title: w.title,
      slug: w.slug,
      description: w.description ?? '',
      price: w.price,
      imageUrl: w.heroImages?.[0] ?? undefined,
    }));
    createStructuredData(createWorkshopsPageSchema(items), 'schema-workshops-page');
  }, [workshopsQuery.data]);

  function handleCategoryChange(id: string) {
    if (id === selectedCategory) return;
    setGridVisible(false);
    setTimeout(() => {
      setSelectedCategory(id);
      setFilterKey(k => k + 1);
      setGridVisible(true);
    }, 180);
  }

  return (
    <div className="min-h-screen bg-background">
      <Navbar />

      {/* ── Hero ── */}
      <section className="relative pt-20 sm:pt-36 md:pt-44 pb-8 sm:pb-16 md:pb-20 [background-color:var(--near-black)] overflow-hidden">
        <div
          className="absolute inset-0 opacity-[0.03]"
          style={{
            backgroundImage: 'repeating-linear-gradient(45deg, #fff 0, #fff 1px, transparent 0, transparent 50%)',
            backgroundSize: '12px 12px',
          }}
        />
        <div className="relative z-10 container">
          <div
            className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-3 sm:gap-5 mb-5 sm:mb-12 lg:mb-16"
            style={{
              opacity: heroVisible ? 1 : 0,
              transform: heroVisible ? 'translateY(0)' : 'translateY(20px)',
              transition: 'opacity 0.6s ease, transform 0.6s ease',
            }}
          >
            <div>
              <p className="text-xs font-bold tracking-[0.2em] uppercase text-white/40 mb-2 sm:mb-4">Our Workshops</p>
              <h1 className="text-2xl sm:text-4xl md:text-5xl lg:text-6xl font-serif font-bold text-white leading-tight">
                {t('workshops.heroTitle')}
              </h1>
            </div>
            <div
              className="max-w-sm w-full lg:w-auto flex flex-col items-start"
              style={{
                opacity: heroVisible ? 1 : 0,
                transform: heroVisible ? 'translateY(0)' : 'translateY(16px)',
                transition: 'opacity 0.6s ease 0.12s, transform 0.6s ease 0.12s',
              }}
            >
              <p className="text-sm sm:text-lg text-white/55 leading-relaxed">
                {t('workshops.heroDesc')}
              </p>
              <button
                className="mt-3 sm:mt-5 self-start inline-flex items-center gap-2 px-4 py-2 sm:px-5 sm:py-2.5 rounded-xl bg-white text-[var(--near-black)] font-semibold text-sm hover:bg-white/90 active:scale-95 transition-all duration-200"
                onClick={() => window.dispatchEvent(new CustomEvent('openQuickBooking'))}
              >
                <Heart className="w-4 h-4 text-rose-500" />
                {t('workshops.bookNow')}
              </button>
            </div>
          </div>

          {/* Stats strip */}
          <div
            className="grid grid-cols-4 gap-px bg-white/10 border border-white/10 rounded-2xl overflow-hidden"
            style={{
              opacity: heroVisible ? 1 : 0,
              transform: heroVisible ? 'translateY(0)' : 'translateY(12px)',
              transition: 'opacity 0.6s ease 0.24s, transform 0.6s ease 0.24s',
            }}
          >
            {STATS.map((s) => (
              <div key={s.label} className="[background-color:var(--near-black)] py-3 sm:py-5 px-2 sm:px-6 flex flex-col items-center gap-0.5 sm:gap-1">
                <span className="text-white/40">{s.icon}</span>
                <p className="text-base sm:text-3xl font-serif font-bold text-white leading-none mt-0.5 sm:mt-1">{s.num}</p>
                <p className="text-[9px] sm:text-xs text-white/40 font-medium text-center leading-tight">{s.label}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ── Filter Bar ── */}
      <section className="sticky top-[60px] sm:top-[64px] z-30 bg-background border-b border-border">
        <div className="container py-3 sm:py-4">
          <div className="flex gap-2 overflow-x-auto pb-1 scrollbar-hide">
            {categories.map((cat) => (
              <button
                key={cat.id}
                onClick={() => handleCategoryChange(cat.id)}
                className={`shrink-0 px-4 py-2 rounded-full text-sm font-semibold transition-all duration-200 ${
                  selectedCategory === cat.id
                    ? 'bg-[var(--near-black)] text-white'
                    : '[color:var(--dark-gray)] hover:[color:var(--near-black)] hover:bg-[var(--light-gray)]'
                }`}
              >
                {cat.label}
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* ── Workshops Grid ── */}
      <section className="section-padding">
        <div className="container">
          {workshopsQuery.isLoading ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 sm:gap-8">
              {[1, 2, 3, 4, 5, 6].map((i) => (
                <WorkshopCardSkeleton key={i} />
              ))}
            </div>
          ) : workshopsQuery.data && workshopsQuery.data.length > 0 ? (
            <div
              key={filterKey}
              className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 sm:gap-8"
              style={{
                opacity: gridVisible ? 1 : 0,
                transition: 'opacity 0.18s ease',
              }}
            >
              {workshopsQuery.data.map((workshop, idx) => (
                <AnimatedCard key={workshop.id} index={idx}>
                  <div className="absolute -top-3 -left-3 z-10 w-8 h-8 rounded-full bg-[var(--near-black)] text-white text-xs font-bold flex items-center justify-center shadow-md">
                    {String(idx + 1).padStart(2, '0')}
                  </div>
                  <WorkshopCard
                    workshop={workshop}
                    origin={origin}
                    onBook={() => window.dispatchEvent(new CustomEvent('openQuickBooking'))}
                    onDetail={(slug) => navigate(`/workshops/${slug}`)}
                  />
                </AnimatedCard>
              ))}
            </div>
          ) : (
            <div className="text-center py-20">
              <div className="w-16 h-16 rounded-full bg-[var(--light-gray)] flex items-center justify-center mx-auto mb-4">
                <Sparkles className="w-7 h-7 [color:var(--cool-gray)]" />
              </div>
              <p className="text-lg [color:var(--dark-gray)]">{t('workshops.noResults')}</p>
            </div>
          )}
        </div>
      </section>

      {/* ── CTA Section ── */}
      <section className="section-padding [background-color:var(--near-black)]">
        <div className="container">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6 py-2">
            <div>
              <p className="text-xs font-bold tracking-[0.2em] uppercase text-white/40 mb-3">Private Session</p>
              <h2 className="text-2xl sm:text-3xl md:text-4xl font-serif font-bold text-white leading-tight">
                {t('workshops.ctaTitle')}
              </h2>
              <p className="text-white/55 mt-2 text-base">
                {t('workshops.ctaDesc')}
              </p>
            </div>
            <div className="flex flex-col sm:flex-row gap-3 shrink-0">
              <button
                className="px-6 py-3 rounded-xl bg-white text-[var(--near-black)] font-bold text-sm hover:bg-white/90 active:scale-95 transition-all duration-200"
                onClick={() => window.dispatchEvent(new CustomEvent('openQuickBooking'))}
              >
                {t('workshops.bookNow')}
              </button>
              <button
                className="px-6 py-3 rounded-xl border border-white/20 text-white font-semibold text-sm hover:bg-white/10 active:scale-95 transition-all duration-200"
                onClick={() => navigate('/contact')}
              >
                {t('workshops.ctaContact')}
              </button>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </div>
  );
}
