import { useState, useEffect } from 'react';
import axios from 'axios';
import type { Product, ProductType } from '@/types/api';

interface ProductWidgetProps {
  productSlug: string;
  buttonText?: string;
}

export function ProductWidget({ productSlug, buttonText = 'Buy Now' }: ProductWidgetProps) {
  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [purchasing, setPurchasing] = useState(false);
  const [purchaseError, setPurchaseError] = useState<string | null>(null);

  useEffect(() => {
    if (!productSlug) {
      setError('No product specified');
      setLoading(false);
      return;
    }

    axios.get('/api/payments/products', { params: { limit: 50 } })
      .then(({ data }) => {
        const found = (data.products as Product[]).find(p => p.slug === productSlug);
        if (found) {
          setProduct(found);
        } else {
          setError('Product not found');
        }
      })
      .catch(() => setError('Failed to load product'))
      .finally(() => setLoading(false));
  }, [productSlug]);

  const handlePurchase = async () => {
    if (!product) return;

    const email = prompt('Enter your email to purchase:');
    if (!email) return;

    setPurchasing(true);
    setPurchaseError(null);
    try {
      const { data } = await axios.post('/api/payments/purchase', {
        productId: product.id,
        buyerEmail: email,
      });
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Failed to start checkout';
      setPurchaseError(msg);
    } finally {
      setPurchasing(false);
    }
  };

  const typeColors: Record<ProductType, string> = {
    DIGITAL: '#1890ff',
    EVENT: '#52c41a',
    DONATION: '#722ed1',
  };

  const styles = {
    card: {
      maxWidth: 380,
      margin: '0 auto',
      borderRadius: 12,
      overflow: 'hidden',
      background: '#1b2838',
      boxShadow: '0 4px 16px rgba(0,0,0,0.3)',
      color: '#fff',
    } as React.CSSProperties,
    imageArea: {
      paddingBottom: '56.25%',
      position: 'relative' as const,
      overflow: 'hidden',
    } as React.CSSProperties,
    image: {
      position: 'absolute' as const,
      top: 0,
      left: 0,
      width: '100%',
      height: '100%',
      objectFit: 'cover' as const,
    } as React.CSSProperties,
    imagePlaceholder: {
      position: 'absolute' as const,
      top: 0,
      left: 0,
      width: '100%',
      height: '100%',
      background: 'linear-gradient(135deg, #9d4edd 0%, #722ed1 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: 48,
    } as React.CSSProperties,
    body: { padding: 16 } as React.CSSProperties,
    tag: (type: ProductType) => ({
      display: 'inline-block',
      padding: '2px 10px',
      background: typeColors[type] || '#666',
      color: '#fff',
      borderRadius: 10,
      fontSize: '0.75rem',
      fontWeight: 600,
      marginBottom: 8,
    } as React.CSSProperties),
    title: { fontSize: '1.1rem', fontWeight: 600, margin: '0 0 6px' } as React.CSSProperties,
    desc: { fontSize: '0.85rem', opacity: 0.7, margin: '0 0 12px', lineHeight: 1.4 } as React.CSSProperties,
    priceRow: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginTop: 12,
    } as React.CSSProperties,
    price: { fontSize: '1.25rem', fontWeight: 700 } as React.CSSProperties,
    buyBtn: {
      padding: '8px 20px',
      background: '#9d4edd',
      color: '#fff',
      border: 'none',
      borderRadius: 6,
      fontWeight: 600,
      cursor: 'pointer',
      opacity: purchasing ? 0.7 : 1,
    } as React.CSSProperties,
    soldOut: {
      padding: '4px 12px',
      background: '#ff4d4f',
      color: '#fff',
      borderRadius: 10,
      fontSize: '0.8rem',
      fontWeight: 600,
    } as React.CSSProperties,
    error: { color: '#ff4d4f', fontSize: '0.85rem', marginTop: 8 } as React.CSSProperties,
  };

  if (loading) {
    return (
      <div style={{ ...styles.card, padding: 40, textAlign: 'center' }}>Loading...</div>
    );
  }

  if (error || !product) {
    return (
      <div style={{ ...styles.card, padding: 24, textAlign: 'center' }}>
        <p style={{ opacity: 0.7, margin: 0 }}>{error || 'Product not found'}</p>
        <a href="/shop" style={{ color: '#9d4edd', fontSize: '0.9rem' }}>Browse shop</a>
      </div>
    );
  }

  const isSoldOut = product.maxPurchases !== null && product.purchaseCount >= (product.maxPurchases ?? 0);

  return (
    <div style={styles.card}>
      <div style={styles.imageArea}>
        {product.imageUrl ? (
          <img src={product.imageUrl} alt={product.title} style={styles.image} />
        ) : (
          <div style={styles.imagePlaceholder}>&#x1F6D2;</div>
        )}
      </div>
      <div style={styles.body}>
        <span style={styles.tag(product.type)}>{product.type}</span>
        <h3 style={styles.title}>{product.title}</h3>
        {product.description && (
          <p style={styles.desc}>{product.description.length > 120 ? product.description.slice(0, 120) + '...' : product.description}</p>
        )}
        <div style={styles.priceRow}>
          <span style={styles.price}>${(product.priceCAD / 100).toFixed(2)}</span>
          {isSoldOut ? (
            <span style={styles.soldOut}>Sold Out</span>
          ) : (
            <button
              type="button"
              style={styles.buyBtn}
              onClick={handlePurchase}
              disabled={purchasing}
            >
              {purchasing ? 'Processing...' : buttonText}
            </button>
          )}
        </div>
        {purchaseError && <div style={styles.error}>{purchaseError}</div>}
      </div>
    </div>
  );
}
