import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { Layout } from '@/components/Layout';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useCart } from '@/contexts/CartContext';
import { toast } from '@/hooks/use-toast';
import { Skeleton } from '@/components/ui/skeleton';

interface Product {
  id: string;
  title: string;
  slug: string;
  type: string;
  description: string;
  content: string;
  price: number;
  sale_price: number | null;
}

export default function ProductDetail() {
  const { slug } = useParams<{ slug: string }>();
  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const { addItem, items } = useCart();

  useEffect(() => {
    if (slug) fetchProduct();
  }, [slug]);

  const fetchProduct = async () => {
    const { data, error } = await supabase
      .from('products')
      .select('*')
      .eq('slug', slug)
      .eq('is_active', true)
      .maybeSingle();

    if (error || !data) {
      toast({ title: 'Error', description: 'Product not found', variant: 'destructive' });
    } else {
      setProduct(data);
    }
    setLoading(false);
  };

  const handleAddToCart = () => {
    if (!product) return;
    addItem({
      id: product.id,
      title: product.title,
      price: product.price,
      sale_price: product.sale_price,
      type: product.type,
    });
    toast({ title: 'Added to cart', description: `${product.title} has been added to your cart` });
  };

  const isInCart = product ? items.some(item => item.id === product.id) : false;

  if (loading) {
    return (
      <Layout>
        <div className="container mx-auto px-4 py-8">
          <Skeleton className="h-10 w-1/2 mb-4" />
          <Skeleton className="h-6 w-1/4 mb-8" />
          <Skeleton className="h-64 w-full" />
        </div>
      </Layout>
    );
  }

  if (!product) {
    return (
      <Layout>
        <div className="container mx-auto px-4 py-8 text-center">
          <h1 className="text-2xl font-bold">Product not found</h1>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          <div className="flex items-start justify-between mb-6">
            <div>
              <h1 className="text-4xl font-bold mb-2">{product.title}</h1>
              <Badge className="bg-secondary">{product.type}</Badge>
            </div>
            <div className="text-right">
              {product.sale_price ? (
                <div>
                  <span className="text-3xl font-bold">${product.sale_price}</span>
                  <span className="text-muted-foreground line-through ml-2">${product.price}</span>
                </div>
              ) : (
                <span className="text-3xl font-bold">${product.price}</span>
              )}
            </div>
          </div>

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

          <Card className="border-2 border-border mb-6">
            <CardContent className="pt-6">
              <div 
                className="prose max-w-none"
                dangerouslySetInnerHTML={{ __html: product.content || '<p>No content available</p>' }}
              />
            </CardContent>
          </Card>

          <Button 
            onClick={handleAddToCart} 
            disabled={isInCart}
            size="lg"
            className="shadow-sm"
          >
            {isInCart ? 'Already in Cart' : 'Add to Cart'}
          </Button>
        </div>
      </div>
    </Layout>
  );
}
