import type { NextPage } from 'next';
import Head from 'next/head';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/router';
import toast from 'react-hot-toast';
import {
  CATALOG_PRODUCT_GRID_CLASS,
  CatalogProductCard,
  CatalogToolbar,
  formatProductCount,
  type CatalogProduct,
  type CatalogSortMode,
} from '../components/CatalogProductCard';

interface WishlistItem {
  id: number;
  productId: number;
  productName: string;
  brandName: string;
  primaryImage: string;
  variantId: number;
  variantLabel: string;
  volumeMl: string;
  currentPrice: number;
  addedAt: string;
}

const Wishlist: NextPage = () => {
  const { status } = useSession();
  const router = useRouter();
  const [wishlistItems, setWishlistItems] = useState<WishlistItem[]>([]);
  const [products, setProducts] = useState<Map<number, CatalogProduct>>(new Map());
  const [loading, setLoading] = useState(true);
  const [displayCount, setDisplayCount] = useState(12);
  const [sortBy, setSortBy] = useState<CatalogSortMode>('newest');

  useEffect(() => {
    if (status === 'unauthenticated') {
      void router.push('/login');
      return;
    }

    if (status === 'authenticated') {
      void fetchWishlist();
    }
  }, [status, router]);

  const fetchWishlist = async () => {
    try {
      setLoading(true);
      const [wishlistResponse, productsResponse] = await Promise.all([
        fetch('/api/wishlist'),
        fetch('/api/products'),
      ]);

      if (wishlistResponse.ok) {
        const wishlistData = await wishlistResponse.json() as WishlistItem[];
        setWishlistItems(wishlistData);

        if (productsResponse.ok) {
          const allProducts = await productsResponse.json() as CatalogProduct[];
          setProducts(new Map(allProducts.map((product) => [product.id, product])));
        }
      } else if (wishlistResponse.status === 401) {
        void router.push('/login');
      }
    } catch {
      toast.error('Chyba při načítání oblíbených');
    } finally {
      setLoading(false);
    }
  };

  const handleRemoveItem = async (itemId: number) => {
    try {
      const response = await fetch(`/api/wishlist?itemId=${itemId}`, { method: 'DELETE' });
      if (response.ok) {
        setWishlistItems((current) => current.filter((item) => item.id !== itemId));
        toast.success('Odebráno z oblíbených');
      } else {
        toast.error('Chyba při odebírání');
      }
    } catch {
      toast.error('Chyba při odebírání');
    }
  };

  const sortedItems = [...wishlistItems].sort((a, b) => {
    if (sortBy === 'cheapest') return a.currentPrice - b.currentPrice;
    if (sortBy === 'most_expensive') return b.currentPrice - a.currentPrice;
    return new Date(b.addedAt).getTime() - new Date(a.addedAt).getTime();
  });

  if (status === 'loading' || loading) {
    return <section className="w-full bg-luxury-dark py-28 text-center text-luxury-gold">Načítání oblíbených…</section>;
  }

  if (status === 'unauthenticated') return null;

  if (sortedItems.length === 0) {
    return (
      <>
        <Head>
          <title>Oblíbené | Vystříkejto.cz</title>
          <meta name="robots" content="noindex,nofollow,noarchive" />
        </Head>
        <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">
          <div className="mx-auto max-w-[1600px]">
            <header className="mb-10">
              <p className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-luxury-gold">Moje sbírka</p>
              <h1 className="text-4xl font-black tracking-[-0.035em] text-luxury-light sm:text-5xl lg:text-6xl">Oblíbené parfémy</h1>
            </header>
            <div className="flex flex-col items-center justify-center border-t border-luxury-light/15 py-20 text-center">
              <div className="mb-8 flex h-24 w-24 items-center justify-center rounded-full bg-luxury-gold/10">
                <HeartIcon />
              </div>
              <h2 className="mb-2 text-2xl font-bold text-luxury-light">Nemáte žádné oblíbené produkty</h2>
              <p className="mb-8 max-w-md text-luxury-light/60">Přidejte si své oblíbené parfémy a vraťte se k nim později.</p>
              <Link href="/#vune" className="min-h-12 bg-luxury-gold px-8 py-3 text-sm font-bold uppercase tracking-wider text-luxury-dark transition-colors hover:bg-yellow-300">Procházet produkty</Link>
            </div>
          </div>
        </section>
      </>
    );
  }

  return (
    <>
      <Head>
        <title>Oblíbené | Vystříkejto.cz</title>
        <meta name="robots" content="noindex,nofollow,noarchive" />
      </Head>
      <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">
        <div className="mx-auto max-w-[1600px]">
          <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">Moje sbírka</p>
              <h1 className="text-4xl font-black tracking-[-0.035em] text-luxury-light sm:text-5xl lg:text-6xl">Oblíbené parfémy</h1>
            </div>
            <span className="hidden text-xs text-luxury-light/45 sm:block">{formatProductCount(sortedItems.length)}</span>
          </header>

          <CatalogToolbar count={sortedItems.length} sortBy={sortBy} onSortChange={setSortBy} />

          <div className={CATALOG_PRODUCT_GRID_CLASS}>
            {sortedItems.slice(0, displayCount).map((item) => {
              const product = products.get(item.productId);
              if (!product) return null;

              return (
                <CatalogProductCard
                  key={item.id}
                  product={product}
                  wishlistActive
                  onWishlist={() => handleRemoveItem(item.id)}
                />
              );
            })}
          </div>

          {displayCount < sortedItems.length && (
            <div className="mt-12 flex justify-center">
              <button
                type="button"
                onClick={() => setDisplayCount((current) => current + 12)}
                className="min-h-12 border border-luxury-light/20 px-7 text-xs font-bold uppercase tracking-[0.1em] text-luxury-light transition-colors hover:border-luxury-gold hover:text-luxury-gold"
              >
                Načíst více produktů
              </button>
            </div>
          )}
        </div>
      </section>
    </>
  );
};

function HeartIcon() {
  return <svg className="h-12 w-12 text-luxury-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78Z" /></svg>;
}

export default Wishlist;
