'use client';

import { useState, useEffect } from 'react';
import { ThemeProvider } from '@/lib/theme/ThemeProvider';
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';
import FooterLogoReveal from '@/components/sections/footer/FooterLogoReveal';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';

interface Product {
  id: string;
  name: string;
  description: string;
  images: string[];
  default_price: {
    id: string;
    unit_amount: number;
    currency: string;
  };
}

interface CheckoutSession {
  url: string;
}

export default function ShopPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [processingItem, setProcessingItem] = useState<string | null>(null);

  useEffect(() => {
    fetchProducts();
  }, []);

  const fetchProducts = async () => {
    try {
      setLoading(true);
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/stripe/project/products?projectId=da31f455-3d23-4140-9060-5109263c469e&expandDefaultPrice=true`
      );
      
      if (!response.ok) {
        throw new Error('Failed to fetch products');
      }
      
      const data = await response.json();
      setProducts(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  const handleBuyNow = async (product: Product) => {
    try {
      setProcessingItem(product.id);
      
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/stripe/project/checkout-session`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            projectId: 'da31f455-3d23-4140-9060-5109263c469e',
            items: [{ priceId: product.default_price.id, quantity: 1 }],
            successUrl: window.location.origin + '/shop?success=true',
            cancelUrl: window.location.origin + '/shop?canceled=true'
          })
        }
      );
      
      if (!response.ok) {
        throw new Error('Failed to create checkout session');
      }
      
      const session: CheckoutSession = await response.json();
      window.location.href = session.url;
    } catch (err) {
      console.error('Checkout error:', err);
      alert('Failed to start checkout. Please try again.');
    } finally {
      setProcessingItem(null);
    }
  };

  const formatPrice = (amount: number, currency: string) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency.toUpperCase(),
    }).format(amount / 100);
  };

  const truncateDescription = (description: string, maxLength: number = 100) => {
    if (description.length <= maxLength) return description;
    return description.substring(0, maxLength) + '...';
  };

  return (
    <ThemeProvider
      defaultButtonVariant="expand-hover"
      defaultTextAnimation="entrance-slide"
      borderRadius="sharp"
      contentWidth="smallMedium"
      sizing="mediumLarge"
      background="aurora"
      cardStyle="elevated"
      primaryButtonStyle="shadow"
      secondaryButtonStyle="glass"
      headingFontWeight="extrabold"
    >
      <div className="min-h-screen flex flex-col">
        <NavbarStyleCentered
          brandName="Baruga"
          navItems={[
            { name: "Home", id: "/" },
            { name: "About", id: "about" },
            { name: "Products", id: "products" },
            { name: "Visit Us", id: "contact" },
            { name: "FAQ", id: "faq" },
            { name: "Shop", id: "/shop" }
          ]}
          button={{ text: "Order Online", href: "contact" }}
        />
        
        <main className="flex-1 container mx-auto px-4 py-8">
          <div className="mb-8">
            <h1 className="text-4xl font-extrabold text-center mb-4">Our Shop</h1>
            <p className="text-center text-muted-foreground max-w-2xl mx-auto">
              Discover our premium products and enjoy secure checkout with Stripe.
            </p>
          </div>

          {loading && (
            <div className="flex justify-center items-center py-16">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">Loading products...</span>
            </div>
          )}

          {error && (
            <div className="text-center py-16">
              <p className="text-destructive mb-4">Error: {error}</p>
              <Button onClick={fetchProducts}>Try Again</Button>
            </div>
          )}

          {!loading && !error && products.length === 0 && (
            <div className="text-center py-16">
              <p className="text-muted-foreground">No products available at the moment.</p>
            </div>
          )}

          {!loading && !error && products.length > 0 && (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {products.map((product) => (
                <Card key={product.id} className="flex flex-col">
                  <CardHeader className="p-0">
                    {product.images && product.images.length > 0 && (
                      <div className="aspect-square overflow-hidden rounded-t-lg">
                        <img
                          src={product.images[0]}
                          alt={product.name}
                          className="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
                        />
                      </div>
                    )}
                  </CardHeader>
                  <CardContent className="flex-1 p-4">
                    <CardTitle className="text-lg mb-2">{product.name}</CardTitle>
                    <CardDescription className="mb-4">
                      {truncateDescription(product.description)}
                    </CardDescription>
                    <div className="text-xl font-bold text-primary">
                      {formatPrice(product.default_price.unit_amount, product.default_price.currency)}
                    </div>
                  </CardContent>
                  <CardFooter className="p-4 pt-0">
                    <Button
                      className="w-full"
                      onClick={() => handleBuyNow(product)}
                      disabled={processingItem === product.id}
                    >
                      {processingItem === product.id ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Processing...
                        </>
                      ) : (
                        'Buy Now'
                      )}
                    </Button>
                  </CardFooter>
                </Card>
              ))}
            </div>
          )}

          {/* Success/Cancel messages */}
          {typeof window !== 'undefined' && (
            <>
              {new URLSearchParams(window.location.search).get('success') && (
                <div className="fixed top-4 right-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded z-50">
                  Payment successful! Thank you for your purchase.
                </div>
              )}
              {new URLSearchParams(window.location.search).get('canceled') && (
                <div className="fixed top-4 right-4 bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded z-50">
                  Payment was canceled. You can try again anytime.
                </div>
              )}
            </>
          )}
        </main>

        <FooterLogoReveal
          logoText="Baruga"
          leftLink={{ text: "Privacy Policy", href: "#privacy" }}
          rightLink={{ text: "Contact Us", href: "contact" }}
        />
      </div>
    </ThemeProvider>
  );
}