import React, { useState, useEffect } from 'react';
import { supabase } from '../lib/supabase';

interface TicketType {
  id: string;
  name: string;
  price: number;
  quantity_available: number;
  quantity_sold: number;
  description?: string;
  is_active: boolean;
}

interface Event {
  id: string;
  title: string;
  venue: string;
  start_time: string;
  slug: string;
}

interface QuickTicketPurchaseProps {
  event: Event;
  onClose: () => void;
  onPurchaseStart: (ticketTypeId: string, quantity: number) => void;
  className?: string;
}

const QuickTicketPurchase: React.FC<QuickTicketPurchaseProps> = ({
  event,
  onClose,
  onPurchaseStart,
  className = ''
}) => {
  const [ticketTypes, setTicketTypes] = useState<TicketType[]>([]);
  const [selectedTicketType, setSelectedTicketType] = useState<string | null>(null);
  const [quantity, setQuantity] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadTicketTypes();
  }, [event.id]);

  const loadTicketTypes = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const { data, error } = await supabase
        .from('ticket_types')
        .select('*')
        .eq('event_id', event.id)
        .eq('is_active', true)
        .order('price');

      if (error) throw error;

      const activeTicketTypes = data?.filter(tt => 
        (tt.quantity_available === null || tt.quantity_available > (tt.quantity_sold || 0))
      ) || [];

      setTicketTypes(activeTicketTypes);
      
      // Auto-select first available ticket type
      if (activeTicketTypes.length > 0) {
        setSelectedTicketType(activeTicketTypes[0].id);
      }
    } catch (_err) {
      console.error('Failed to load ticket options:', _err);
      setError('Failed to load ticket options');
    } finally {
      setIsLoading(false);
    }
  };

  const getAvailableQuantity = (ticketType: TicketType) => {
    if (ticketType.quantity_available === null) return 999; // Unlimited
    return ticketType.quantity_available - (ticketType.quantity_sold || 0);
  };

  const handlePurchase = () => {
    if (!selectedTicketType) return;
    
    onPurchaseStart(selectedTicketType, quantity);
  };

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD'
    }).format(price);
  };

  const formatEventTime = (startTime: string) => {
    const date = new Date(startTime);
    return date.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit'
    });
  };

  const selectedTicket = ticketTypes.find(tt => tt.id === selectedTicketType);
  const totalPrice = selectedTicket ? selectedTicket.price * quantity : 0;
  const availableQuantity = selectedTicket ? getAvailableQuantity(selectedTicket) : 0;

  return (
    <div className={`fixed inset-0 flex items-center justify-center p-4 z-50 backdrop-blur-sm ${className}`} style={{background: 'var(--ui-bg-overlay)'}}>
      <div className="rounded-lg shadow-xl max-w-md w-full max-h-screen overflow-y-auto backdrop-blur-xl" style={{background: 'var(--ui-bg-elevated)', border: '1px solid var(--ui-border-primary)'}}>
        {/* Header */}
        <div className="flex items-center justify-between p-6" style={{borderBottom: '1px solid var(--ui-border-secondary)'}}>
          <h2 className="text-xl font-semibold" style={{color: 'var(--ui-text-primary)'}}>Quick Purchase</h2>
          <button
            onClick={onClose}
            className="transition-colors"
            style={{color: 'var(--ui-text-muted)'}}
            onMouseEnter={(e) => e.target.style.color = 'var(--ui-text-secondary)'}
            onMouseLeave={(e) => e.target.style.color = 'var(--ui-text-muted)'}
          >
            <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Event Info */}
        <div className="p-6 backdrop-blur-lg" style={{borderBottom: '1px solid var(--ui-border-secondary)', background: 'var(--ui-bg-secondary)'}}>
          <h3 className="text-lg font-medium mb-2" style={{color: 'var(--ui-text-primary)'}}>{event.title}</h3>
          <div className="space-y-1 text-sm" style={{color: 'var(--ui-text-secondary)'}}>
            <div className="flex items-center">
              <svg className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
              {event.venue}
            </div>
            <div className="flex items-center">
              <svg className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              {formatEventTime(event.start_time)}
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="p-6">
          {isLoading && (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 mx-auto" style={{borderColor: 'var(--glass-text-accent)'}}></div>
              <p className="mt-2" style={{color: 'var(--ui-text-secondary)'}}>Loading ticket options...</p>
            </div>
          )}

          {error && (
            <div className="rounded-lg p-4 mb-4 backdrop-blur-lg" style={{background: 'var(--error-bg)', border: '1px solid var(--error-border)'}}>
              <div className="flex items-center">
                <svg className="h-5 w-5 mr-2" style={{color: 'var(--error-color)'}} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                </svg>
                <span style={{color: 'var(--error-color)'}}>{error}</span>
              </div>
            </div>
          )}

          {!isLoading && !error && (
            <>
              {ticketTypes.length === 0 ? (
                <div className="text-center py-8">
                  <svg className="mx-auto h-12 w-12" style={{color: 'var(--ui-text-muted)'}} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <h3 className="mt-2 text-sm font-medium" style={{color: 'var(--ui-text-primary)'}}>No tickets available</h3>
                  <p className="mt-1 text-sm" style={{color: 'var(--ui-text-tertiary)'}}>
                    This event is currently sold out or tickets are not yet on sale.
                  </p>
                </div>
              ) : (
                <>
                  {/* Ticket Type Selection */}
                  <div className="mb-6">
                    <label className="block text-sm font-medium mb-3" style={{color: 'var(--ui-text-secondary)'}}>
                      Select Ticket Type
                    </label>
                    <div className="space-y-2">
                      {ticketTypes.map(ticketType => {
                        const available = getAvailableQuantity(ticketType);
                        const isUnavailable = available <= 0;
                        
                        return (
                          <div
                            key={ticketType.id}
                            className="border rounded-lg p-3 cursor-pointer transition-colors backdrop-blur-lg"
                            style={{
                              borderColor: selectedTicketType === ticketType.id
                                ? 'var(--glass-border-focus)'
                                : isUnavailable
                                ? 'var(--ui-border-secondary)'
                                : 'var(--ui-border-primary)',
                              background: selectedTicketType === ticketType.id
                                ? 'var(--glass-bg-lg)'
                                : isUnavailable
                                ? 'var(--ui-bg-secondary)'
                                : 'var(--ui-bg-elevated)',
                              opacity: isUnavailable ? 0.5 : 1,
                              cursor: isUnavailable ? 'not-allowed' : 'pointer'
                            }}
                            onMouseEnter={(e) => {
                              if (!isUnavailable && selectedTicketType !== ticketType.id) {
                                e.target.style.borderColor = 'var(--glass-border-focus)';
                              }
                            }}
                            onMouseLeave={(e) => {
                              if (!isUnavailable && selectedTicketType !== ticketType.id) {
                                e.target.style.borderColor = 'var(--ui-border-primary)';
                              }
                            }}
                            onClick={() => !isUnavailable && setSelectedTicketType(ticketType.id)}
                          >
                            <div className="flex items-center justify-between">
                              <div className="flex items-center">
                                <input
                                  type="radio"
                                  checked={selectedTicketType === ticketType.id}
                                  onChange={() => setSelectedTicketType(ticketType.id)}
                                  disabled={isUnavailable}
                                  className="mr-3"
                                />
                                <div>
                                  <div className="font-medium" style={{color: 'var(--ui-text-primary)'}}>{ticketType.name}</div>
                                  {ticketType.description && (
                                    <div className="text-sm" style={{color: 'var(--ui-text-secondary)'}}>{ticketType.description}</div>
                                  )}
                                </div>
                              </div>
                              <div className="text-right">
                                <div className="font-semibold" style={{color: 'var(--ui-text-primary)'}}>
                                  {formatPrice(ticketType.price)}
                                </div>
                                <div className="text-sm" style={{color: 'var(--ui-text-tertiary)'}}>
                                  {isUnavailable ? 'Sold Out' : 
                                   available < 10 ? `${available} left` : 'Available'}
                                </div>
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>

                  {/* Quantity Selection */}
                  {selectedTicket && (
                    <div className="mb-6">
                      <label className="block text-sm font-medium mb-2" style={{color: 'var(--ui-text-secondary)'}}>
                        Quantity
                      </label>
                      <div className="flex items-center space-x-3">
                        <button
                          onClick={() => setQuantity(Math.max(1, quantity - 1))}
                          disabled={quantity <= 1}
                          className="w-8 h-8 rounded-full border flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed transition-colors backdrop-blur-lg"
                          style={{
                            borderColor: 'var(--ui-border-primary)',
                            background: 'var(--ui-bg-elevated)'
                          }}
                          onMouseEnter={(e) => {
                            if (!e.target.disabled) {
                              e.target.style.background = 'var(--ui-bg-secondary)';
                            }
                          }}
                          onMouseLeave={(e) => {
                            if (!e.target.disabled) {
                              e.target.style.background = 'var(--ui-bg-elevated)';
                            }
                          }}
                        >
                          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
                          </svg>
                        </button>
                        <span className="w-8 text-center font-medium" style={{color: 'var(--ui-text-primary)'}}>{quantity}</span>
                        <button
                          onClick={() => setQuantity(Math.min(availableQuantity, quantity + 1))}
                          disabled={quantity >= availableQuantity}
                          className="w-8 h-8 rounded-full border flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed transition-colors backdrop-blur-lg"
                          style={{
                            borderColor: 'var(--ui-border-primary)',
                            background: 'var(--ui-bg-elevated)'
                          }}
                          onMouseEnter={(e) => {
                            if (!e.target.disabled) {
                              e.target.style.background = 'var(--ui-bg-secondary)';
                            }
                          }}
                          onMouseLeave={(e) => {
                            if (!e.target.disabled) {
                              e.target.style.background = 'var(--ui-bg-elevated)';
                            }
                          }}
                        >
                          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                          </svg>
                        </button>
                      </div>
                      <p className="text-sm mt-1" style={{color: 'var(--ui-text-tertiary)'}}>
                        Max {availableQuantity} tickets available
                      </p>
                    </div>
                  )}

                  {/* Total */}
                  {selectedTicket && (
                    <div className="mb-6 p-4 rounded-lg backdrop-blur-lg" style={{background: 'var(--ui-bg-secondary)'}}>
                      <div className="flex justify-between items-center">
                        <span className="font-medium" style={{color: 'var(--ui-text-primary)'}}>Total</span>
                        <span className="text-xl font-bold" style={{color: 'var(--ui-text-primary)'}}>
                          {formatPrice(totalPrice)}
                        </span>
                      </div>
                      <div className="text-sm mt-1" style={{color: 'var(--ui-text-tertiary)'}}>
                        {quantity} × {selectedTicket.name} @ {formatPrice(selectedTicket.price)}
                      </div>
                    </div>
                  )}
                </>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        {!isLoading && !error && ticketTypes.length > 0 && (
          <div className="px-6 py-4 flex space-x-3 backdrop-blur-lg" style={{borderTop: '1px solid var(--ui-border-secondary)', background: 'var(--ui-bg-secondary)'}}>
            <button
              onClick={onClose}
              className="flex-1 px-4 py-2 border rounded-md text-sm font-medium transition-colors backdrop-blur-lg"
              style={{
                borderColor: 'var(--ui-border-primary)',
                color: 'var(--ui-text-secondary)',
                background: 'var(--ui-bg-elevated)'
              }}
              onMouseEnter={(e) => e.target.style.background = 'var(--ui-bg-secondary)'}
              onMouseLeave={(e) => e.target.style.background = 'var(--ui-bg-elevated)'}
            >
              Cancel
            </button>
            <button
              onClick={handlePurchase}
              disabled={!selectedTicketType || availableQuantity <= 0}
              className="flex-1 px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              style={{
                background: 'linear-gradient(to right, var(--glass-text-accent), var(--premium-gold))',
                color: 'var(--glass-text-primary)'
              }}
              onMouseEnter={(e) => {
                if (!e.target.disabled) {
                  e.target.style.background = 'linear-gradient(to right, var(--glass-border-focus), var(--premium-gold-border))'
                }
              }}
              onMouseLeave={(e) => {
                if (!e.target.disabled) {
                  e.target.style.background = 'linear-gradient(to right, var(--glass-text-accent), var(--premium-gold))'
                }
              }}
            >
              Continue to Checkout
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default QuickTicketPurchase;