import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ShoppingCart, CheckCircle, Menu } from "lucide-react";
import { products, formatPrice } from "@shared/products";
import { useLocation } from "wouter";

export default function Shop() {
  const [, navigate] = useLocation();
  const [showMobileMenu, setShowMobileMenu] = useState(false);

  const handleAddToCart = (productId: string) => {
    // Store cart in both localStorage (persistent) and sessionStorage (immediate)
    let cartItems = [];
    
    // Try localStorage first (persistent across sessions)
    const storedCart = localStorage.getItem("cart");
    if (storedCart) {
      try {
        cartItems = JSON.parse(storedCart);
      } catch (e) {
        console.error('Failed to parse localStorage cart:', e);
      }
    }
    
    const existing = cartItems.find((item: any) => item.productId === productId);
    
    if (existing) {
      existing.quantity += 1;
    } else {
      cartItems.push({ productId, quantity: 1 });
    }
    
    // Save to both storages for redundancy
    localStorage.setItem("cart", JSON.stringify(cartItems));
    sessionStorage.setItem("pendingCartItems", JSON.stringify(cartItems));
    
    // Navigate to checkout
    navigate("/checkout");
  };

  return (
    <div className="min-h-screen flex flex-col bg-background">
      {/* Header */}
      <header className="sticky top-0 z-50 bg-background border-b border-border">
        <div className="container flex items-center justify-between py-4">
          <div className="flex items-center gap-8">
            <a href="/" className="flex items-center gap-2 hover:opacity-80 transition-opacity">
              <img
                src="https://d2xsxph8kpxj0f.cloudfront.net/310519663183885862/MATkf3xTWf8GjeFQgJipRW/1775460623330_863f878b.jpg"
                alt="Modemanagement Logo"
                className="h-12 w-auto"
              />
            </a>
          </div>
          <nav className="hidden md:flex items-center gap-6">
            <a href="/#kpi-dashboard" className="text-foreground hover:text-primary font-semibold transition-colors">KPI Calculator</a>
            <a href="/#wat-zeggen-mijn-klanten" className="text-foreground hover:text-primary font-semibold transition-colors">Testimonials</a>
            <a href="/#inkoopplanning" className="text-foreground hover:text-primary font-semibold transition-colors">Inkoopplanning</a>
            <a href="/#korting-calculator" className="text-foreground hover:text-primary font-semibold transition-colors">Korting Calculator</a>
            <a href="/#gratis-cursus" className="text-foreground hover:text-primary font-semibold transition-colors">Gratis Cursus</a>
            <a href="/shop" className="text-primary font-semibold">Webshop</a>
            <a href="/#gratis-kpi-analyse" className="text-foreground hover:text-primary font-semibold transition-colors">Gratis Analyse</a>
          </nav>
          <div className="flex items-center gap-4">
            <button
              onClick={() => setShowMobileMenu(!showMobileMenu)}
              className="md:hidden flex items-center justify-center w-10 h-10 rounded-lg hover:bg-secondary transition-colors"
              aria-label="Menu"
            >
              <Menu className="w-6 h-6" />
            </button>
            <a href="https://koalendar.com/e/cor-van-laar" target="_blank" rel="noopener noreferrer" className="hidden md:inline-block">
              <Button className="bg-primary text-primary-foreground hover:bg-primary/90">
                📞 Gratis belafspraak
              </Button>
            </a>
          </div>
        </div>
        {showMobileMenu && (
          <div className="md:hidden border-t border-border bg-background/95 backdrop-blur">
            <div className="container py-4 space-y-3">
              <a href="/#kpi-dashboard" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                KPI Calculator
              </a>
              <a href="/#wat-zeggen-mijn-klanten" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Testimonials
              </a>
              <a href="/#inkoopplanning" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Inkoopplanning
              </a>
              <a href="/#korting-calculator" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Korting Calculator
              </a>
              <a href="/#gratis-cursus" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Gratis Cursus
              </a>
              <a href="/shop" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Webshop
              </a>
              <a href="/#gratis-kpi-analyse" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Gratis Analyse
              </a>
              <Button className="luxury-button w-full" onClick={() => { window.open('https://koalendar.com/e/cor-van-laar', '_blank'); setShowMobileMenu(false); }}>
                📞 Gratis belafspraak
              </Button>
            </div>
          </div>
        )}
      </header>

      <div className="flex flex-1 flex-col lg:flex-row">
        {/* Products Grid */}
        <div className="flex-1 container py-12 lg:border-r lg:border-border">
          <div className="space-y-8">
            <div className="text-center space-y-4">
              <h1 className="text-5xl font-bold font-serif text-foreground">
                Modemanagement Webshop
              </h1>
              <p className="text-xl text-muted-foreground">
                Kies het perfecte pakket voor jouw bedrijf
              </p>
            </div>

            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
              {products.map((product) => (
                <Card
                  key={product.id}
                  className={`flex flex-col p-6 transition-all hover:shadow-lg ${
                    product.highlighted ? "border-primary border-2" : ""
                  }`}
                >
                  {product.highlighted && (
                    <div className="mb-4 inline-block bg-primary text-primary-foreground px-3 py-1 rounded-full text-sm font-semibold">
                      Populair
                    </div>
                  )}

                  <h3 className="text-2xl font-bold font-serif text-foreground mb-2">
                    {product.name}
                  </h3>

                  <div className="mb-4">
                    <div className="flex items-baseline gap-2">
                      <span className="text-4xl font-bold text-primary">
                        €{(product.price / 100).toFixed(2)}
                      </span>
                      {product.priceNote && (
                        <span className="text-sm text-muted-foreground">{product.priceNote}</span>
                      )}
                      {product.duration && !product.priceNote && (
                        <span className="text-sm text-muted-foreground">{product.duration}</span>
                      )}
                    </div>
                  </div>

                  <p className="text-foreground/70 mb-6">{product.description}</p>

                  <div className="space-y-3 mb-6 flex-1">
                    {product.features.map((feature, idx) => (
                      <div key={idx} className="flex gap-2">
                        <CheckCircle className="w-5 h-5 text-primary flex-shrink-0 mt-0.5" />
                        <span className="text-sm text-foreground">{feature}</span>
                      </div>
                    ))}
                  </div>

                  <div className="flex gap-2">
                    {product.externalLink ? (
                      <a
                        href={product.externalLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex-1"
                      >
                        <Button className="w-full bg-primary text-primary-foreground hover:bg-primary/90">
                          Klik hier
                        </Button>
                      </a>
                    ) : (
                      <Button
                        onClick={() => handleAddToCart(product.id)}
                        className="flex-1 bg-primary text-primary-foreground hover:bg-primary/90"
                      >
                        <ShoppingCart className="w-4 h-4 mr-2" />
                        In winkelwagen
                      </Button>
                    )}
                  </div>
                </Card>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
