'use client';

import { useState, useEffect } from 'react';
import { ThemeProvider } from '@/components/ui/theme-provider';
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';
import FooterLogoReveal from '@/components/sections/footer/FooterLogoReveal';
import { Card, CardContent, 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 [checkingOut, setCheckingOut] = useState<string | null>(null);

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

  const fetchProducts = async () => {
    try {
      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('Failed to load products. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  const handleCheckout = async (priceId: string) => {
    setCheckingOut(priceId);
    try {
      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, 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 initiate checkout. Please try again.');
    } finally {
      setCheckingOut(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) return '';
    return description.length > maxLength 
      ? description.substring(0, maxLength) + '...' 
      : description;
  };

  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-grow container mx-auto px-4 py-8">
          <div className="text-center mb-12">
            <h1 className="text-4xl md:text-5xl font-extrabold mb-4 bg-gradient-to-r from-primary to-primary/70 bg-clip-text text-transparent">
              Our Products
            </h1>
            <p className="text-lg text-muted-foreground max-w-2xl mx-auto">
              Discover our amazing collection of products. Shop now and enjoy fast delivery!
            </p>
          </div>

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

          {error && (
            <div className="text-center py-20">
              <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-8 max-w-md mx-auto">
                <h2 className="text-xl font-semibold text-destructive mb-2">Error Loading Products</h2>
                <p className="text-destructive/80">{error}</p>
                <Button 
                  onClick={fetchProducts} 
                  variant="outline" 
                  className="mt-4"
                >
                  Try Again
                </Button>
              </div>
            </div>
          )}

          {!loading && !error && products.length === 0 && (
            <div className="text-center py-20">
              <div className="bg-muted/10 border border-muted/20 rounded-lg p-8 max-w-md mx-auto">
                <h2 className="text-xl font-semibold mb-2">No Products Found</h2>
                <p className="text-muted-foreground">We're currently updating our inventory. Please check back soon!</p>
              </div>
            </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="group hover:shadow-lg transition-all duration-300">
                  <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 group-hover:scale-105 transition-transform duration-300"
                        />
                      </div>
                    ) : (
                      <div className="aspect-square bg-muted/20 rounded-t-lg flex items-center justify-center">
                        <span className="text-muted-foreground text-4xl">📦</span>
                      </div>
                    )}
                  </CardHeader>
                  <CardContent className="p-4">
                    <CardTitle className="text-lg mb-2 line-clamp-2">{product.name}</CardTitle>
                    {product.description && (
                      <p className="text-sm text-muted-foreground mb-3 line-clamp-3">
                        {truncateDescription(product.description)}
                      </p>
                    )}
                    {product.default_price && (
                      <div className="text-2xl 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={() => product.default_price && handleCheckout(product.default_price.id)}
                      disabled={!product.default_price || checkingOut === product.default_price?.id}
                    >
                      {checkingOut === product.default_price?.id ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Processing...
                        </>
                      ) : (
                        'Buy Now'
                      )}
                    </Button>
                  </CardFooter>
                </Card>
              ))}
            </div>
          )}
        </main>

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