import React, { useEffect, useState } from 'react';
import { GetServerSideProps } from 'next';
import Seo from '../components/Seo';
import Breadcrumbs, { breadcrumbsJsonLd } from '../components/Breadcrumbs';
import { SITE_URL } from '../lib/seo';
import { fetchFromApi } from '../lib/serverFetch';
import ProductListing from '../components/ProductListing';
import { formatProductCount, type CatalogProduct } from '../components/CatalogProductCard';

interface ClearancePageProps {
  initialProducts: CatalogProduct[];
}

const ClearancePage: React.FC<ClearancePageProps> = ({ initialProducts }) => {
  const [products, setProducts] = useState<CatalogProduct[]>(initialProducts);
  const [loading, setLoading] = useState(initialProducts.length === 0);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (initialProducts.length > 0) {
      setProducts(initialProducts);
      setLoading(false);
      return;
    }

    const fetchProducts = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/products?stock=1');
        if (!response.ok) {
          throw new Error('Failed to fetch products');
        }
        const data: CatalogProduct[] = await response.json();
        setProducts(data);
        setError(null);
      } catch (err) {
        setError('Nepodařilo se načíst produkty');
      } finally {
        setLoading(false);
      }
    };

    fetchProducts();
  }, [initialProducts]);

  if (loading) {
    return (
      <section className="w-full bg-luxury-dark py-12 md:py-16 pt-20 md:pt-48">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <p className="text-luxury-gold">Načítání produktů...</p>
          </div>
        </div>
      </section>
    );
  }

  if (error) {
    return (
      <section className="w-full bg-luxury-dark py-12 md:py-16 pt-20 md:pt-48">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <p className="text-red-500">{error}</p>
            <p className="text-luxury-light/60 text-sm mt-2">
              Ujistěte se, že jste vyplnili MySQL credentials do .env souboru
            </p>
          </div>
        </div>
      </section>
    );
  }

  if (products.length === 0) {
    return (
      <>
      <Seo
        title="Výprodej celých parfémů | Poslední kusy | Vystříkejto.cz"
        description="Poslední kusy celých originálních parfémů za výhodné ceny. Nakupte, než dojdou."
        canonical={`${SITE_URL}/vyprodej`}
      />
      <section className="w-full bg-luxury-dark py-12 md:py-16 pt-20 md:pt-48">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-10 md:mb-12">
            <p className="text-luxury-gold text-xs sm:text-sm md:text-base font-semibold uppercase tracking-wider mb-1.5 sm:mb-2">
              Výprodej
            </p>
            <h1 className="text-2xl sm:text-3xl md:text-5xl lg:text-6xl font-aptos font-black text-luxury-light mb-3 sm:mb-4">
              Poslední kusy
            </h1>
            <div className="w-10 sm:w-12 h-1 bg-luxury-gold mx-auto" />
          </div>
          <div className="text-center">
            <p className="text-luxury-light/60">Žádné produkty s jedním kusem nejsou k dispozici</p>
          </div>
        </div>
      </section>
      </>
    );
  }

  return (
    <>
      <Seo
        title="Výprodej celých parfémů | Poslední kusy | Vystříkejto.cz"
        description="Poslední kusy celých originálních parfémů za výhodné ceny. Nakupte, než dojdou."
        canonical={`${SITE_URL}/vyprodej`}
        jsonLd={breadcrumbsJsonLd([
          { name: 'Domů', href: '/' },
          { name: 'Výprodej' },
        ])}
      />
      <section className="w-full bg-luxury-dark px-4 pb-20 pt-28 sm:px-6 lg:px-[5vw] lg:pb-24 lg:pt-36" data-section="clearance-products">
        <div className="mx-auto max-w-[1600px]">
          <Breadcrumbs items={[{ name: 'Domů', href: '/' }, { name: 'Výprodej' }]} />
          <header className="mb-10 flex items-end justify-between gap-6">
            <div>
              <p className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-luxury-gold">Výprodej</p>
              <h1 className="text-4xl font-black tracking-[-0.035em] text-luxury-light sm:text-5xl lg:text-6xl">Poslední kusy</h1>
            </div>
            <span className="hidden text-xs text-luxury-light/45 sm:block">{formatProductCount(products.length)}</span>
          </header>
          <ProductListing
            initialProducts={products}
            showHeader={false}
            sectionId="catalog-products"
            dataSection="clearance-products"
          />
        </div>
      </section>
    </>
  );
};

export const getServerSideProps: GetServerSideProps<ClearancePageProps> = async ({ req }) => {
  const products = await fetchFromApi<CatalogProduct[]>(req, '/api/products?stock=1');
  return {
    props: {
      initialProducts: products || [],
    },
  };
};

export default ClearancePage;
