import React from 'react';
import { getProducts, getWooCommerceCategories, extractBrand } from '@/lib/wpgraphql';
import { getStoreSettings } from '@/lib/settings';
import { getQuizData } from '@/lib/quiz';
import Hero from '@/components/home/Hero';
import CategorySection from '@/components/home/CategorySection';
import ReelsSection from '@/components/home/ReelsSection';
import TopSellingSection from '@/components/home/TopSellingSection';
import BrandsSection, { BrandTile } from '@/components/home/BrandsSection';
import CtaBanner from '@/components/home/CtaBanner';
import JustForYou from '@/components/home/JustForYou';
import ReviewsSection from '@/components/home/ReviewsSection';
import QuizSection from '@/components/home/QuizSection';
import TrustBar from '@/components/home/TrustBar';
import ProductCard from '@/components/product/ProductCard';
import { Product } from '@/types/woocommerce';
import { ProductSectionSettings, CustomProductSectionSetting, HomepageSettings } from '@/lib/settings';

export const revalidate = 10;

/** Demo .sec-h header: title + subtitle + "View all" link */
function SecHead({
  title,
  subtitle,
  link,
  linkText,
}: {
  title: string;
  subtitle?: string;
  link?: string;
  linkText?: string;
}) {
  if (!title) return null;
  return (
    <div className="sec-h">
      <div>
        <h2>{title}</h2>
        {subtitle ? <p>{subtitle}</p> : null}
      </div>
      {link ? (
        <a className="link" href={link}>
          {linkText || 'View all →'}
        </a>
      ) : null}
    </div>
  );
}

function filterProducts(products: Product[], category: string, limit: number): Product[] {
  let list = [...(products || [])];
  if (category) {
    list = list.filter((p) => Array.isArray(p?.categories) && p.categories.includes(category));
  }
  return list.slice(0, limit || 5);
}

/** Standard product rail section (products_1, products_2, custom sections) — demo .rail design */
function ProductRailSection({
  settings,
  products,
}: {
  settings: ProductSectionSettings | CustomProductSectionSetting;
  products: Product[];
}) {
  if (!settings?.enabled) return null;
  const items = filterProducts(products, settings.category || '', settings.limit || 5);
  if (items.length === 0) return null;
  const link =
    settings.btn_link || (settings.category ? `/category/${settings.category}` : '/shop');
  return (
    <section className="sec wrap" aria-label={settings.title}>
      <SecHead
        title={settings.title}
        subtitle={settings.subtitle}
        link={link}
        linkText={settings.btn_text || 'View all'}
      />
      <div className="rail prail">
        <div className="rtrack">
          {items.map((p) => (
            <ProductCard
              key={p.id}
              product={p}
              badgeText={settings.badge_enabled !== false ? (settings.badge_tag || '') : ''}
              hideBadge={settings.badge_enabled === false}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

export default async function HomePage() {
  const [settings, allProducts, categories, quizData] = await Promise.all([
    getStoreSettings().catch(() => null),
    getProducts().catch(() => []),
    getWooCommerceCategories().catch(() => []),
    getQuizData().catch(() => null),
  ]);

  // If settings failed entirely, use empty defaults so the page still renders
  const homepage: Partial<HomepageSettings> = settings?.homepage || {};
  const order = (homepage as any).section_order || {};

  // Top selling: highest discount first (proxy for best sellers)
  const topSelling = [...allProducts]
    .sort((a, b) => (b.discountPercent || 0) - (a.discountPercent || 0))
    .slice(0, homepage.top_selling?.limit || 4);

  // Brands derived from WooCommerce products
  const brandMap = new Map<string, BrandTile>();
  allProducts.forEach((p) => {
    const b = extractBrand(p);
    if (b && b.toLowerCase() !== 'hayat supplements') {
      const slug = b
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '');
      const ex = brandMap.get(slug);
      if (ex) ex.count += 1;
      else {
        // Check if a brand image exists in public/images/brands/
        let image: string | undefined;
        try {
          const { existsSync } = require('fs');
          const { join } = require('path');
          if (existsSync(join(process.cwd(), 'public', 'images', 'brands', `${slug}.png`))) {
            image = `/images/brands/${slug}.png`;
          }
        } catch {}
        brandMap.set(slug, { name: b, slug, count: 1, image });
      }
    }
  });
  const brands = Array.from(brandMap.values());

  // Fallbacks keep TS happy when the plugin has no saved values yet
  const topSellingSettings = homepage.top_selling || {
    enabled: true,
    title: 'Top Selling Products',
    subtitle: 'সবচেয়ে বেশি অর্ডার হওয়া পণ্য',
    btn_text: 'View all',
    btn_link: '/shop?sort=popular',
    limit: 4,
  };
  const brandsSettings = homepage.brands || {
    enabled: true,
    title: 'Our Brands',
    subtitle: '',
    btn_text: 'View all',
    btn_link: '/brands',
  };
  const ctaBannerSettings = homepage.cta_banner || {
    enabled: true,
    title: 'ভেষজের শক্তি, প্রতিদিনের সুস্থতায়',
    subtitle: '',
    btn_text: 'Finest Herbs দেখুন',
    btn_link: '/category/finest-herbs',
  };
  // Inactive promo banners (same CtaBanner style) — render when enabled via plugin
  const promoBanner1Settings = homepage.banner_cta_1 || { enabled: false };
  const promoBanner2Settings = homepage.banner_cta_2 || { enabled: false };
  const justForYouSettings = homepage.just_for_you || {
    enabled: true,
    title: 'Just For You',
    subtitle: '',
    limit: 8,
  };

  const sections: { key: string; order: number; render: () => React.ReactNode }[] = [
    {
      key: 'hero',
      order: Number(order.hero) || 1,
      render: () => (homepage.hero?.enabled ? <Hero settings={homepage.hero} /> : null),
    },
    {
      key: 'categories',
      order: Number(order.categories) || 2,
      render: () =>
        homepage.categories?.enabled ? (
          <CategorySection settings={homepage.categories} categories={categories} />
        ) : null,
    },
    {
      key: 'reels',
      order: Number(order.reels) || 3,
      render: () =>
        homepage.reels?.enabled ? (
          <ReelsSection settings={homepage.reels} allProducts={allProducts} />
        ) : null,
    },
    {
      key: 'top_selling',
      order: Number(order.top_selling) || 4,
      render: () => (
        <TopSellingSection settings={topSellingSettings} products={topSelling} />
      ),
    },
    {
      key: 'brands',
      order: Number(order.brands) || 5,
      render: () => <BrandsSection settings={brandsSettings} brands={brands} />,
    },
    {
      key: 'products_1',
      order: Number(order.products_1) || 6,
      render: () => (
        <ProductRailSection settings={homepage.products_1 || { enabled: false } as any} products={allProducts} />
      ),
    },
    {
      key: 'cta_banner',
      order: Number(order.cta_banner) || 7,
      render: () => <CtaBanner settings={ctaBannerSettings} />,
    },
    {
      key: 'products_2',
      order: Number(order.products_2) || 8,
      render: () => (
        <ProductRailSection settings={homepage.products_2 || { enabled: false } as any} products={allProducts} />
      ),
    },
    {
      key: 'quiz',
      order: Number(order.quiz) || 9,
      render: () => {
        const qz = homepage.quiz;
        const on = qz?.enabled === true || (qz?.enabled as unknown) === '1';
        if (!on) return null;
        return (
          <QuizSection
            title={qz?.title || ''}
            settings={qz}
            data={quizData}
            allProducts={allProducts}
          />
        );
      },
    },
    {
      key: 'custom_products',
      order: Number(order.custom_products) || 10,
      render: () => {
        const secs = (homepage.custom_sections || []).filter((s) => s.enabled);
        if (secs.length === 0) return null;
        return (
          <>
            {secs.map((cs, idx) => (
              <ProductRailSection
                key={cs.id || `custom-${idx}`}
                settings={cs}
                products={allProducts}
              />
            ))}
          </>
        );
      },
    },
    {
      key: 'just_for_you',
      order: Number(order.just_for_you) || 11,
      render: () => <JustForYou settings={justForYouSettings} products={allProducts} />,
    },
    {
      key: 'reviews',
      order: Number(order.reviews) || 12,
      render: () =>
        homepage.reviews?.enabled !== false ? (
          <ReviewsSection settings={homepage.reviews} />
        ) : null,
    },
    {
      key: 'trust',
      order: Number(order.trust) || 13,
      render: () => <TrustBar settings={homepage.trust} />,
    },
    {
      key: 'new_arrivals',
      order: Number(order.new_arrivals) || 25,
      render: () => (
        <ProductRailSection settings={homepage.new_arrivals || { enabled: false } as any} products={allProducts} />
      ),
    },
    // Inactive (not in Hayat demo): season, season_2, season_3 —
    // code kept, hidden until needed.
    // Promo banners 1 & 2 use the same CtaBanner component/style as cta_banner.
    {
      key: 'banner_cta_1',
      order: Number(order.banner_cta_1) || 23,
      render: () => <CtaBanner settings={promoBanner1Settings as any} />,
    },
    {
      key: 'banner_cta_2',
      order: Number(order.banner_cta_2) || 24,
      render: () => <CtaBanner settings={promoBanner2Settings as any} />,
    },
  ];

  const sorted = [...sections].sort((a, b) => a.order - b.order);

  return (
    <>
      {sorted.map((s) => (
        <React.Fragment key={s.key}>{s.render()}</React.Fragment>
      ))}
    </>
  );
}
