import React, { useState, useEffect } from 'react';
import type { TicketType, TicketTypeFormData } from '../../lib/ticket-management';
import { createTicketType, updateTicketType } from '../../lib/ticket-management';

interface TicketTypeModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (ticketType: TicketType) => void;
  eventId: string;
  ticketType?: TicketType;
}

export default function TicketTypeModal({ 
  isOpen, 
  onClose, 
  onSave, 
  eventId, 
  ticketType 
}: TicketTypeModalProps) {
  const [formData, setFormData] = useState<TicketTypeFormData>({
    name: '',
    description: '',
    price_cents: 0,
    quantity: 100,
    is_active: true
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (ticketType) {
      setFormData({
        name: ticketType.name,
        description: ticketType.description,
        price_cents: ticketType.price_cents,
        quantity: ticketType.quantity,
        is_active: ticketType.is_active
      });
    } else {
      setFormData({
        name: '',
        description: '',
        price_cents: 0,
        quantity: 100,
        is_active: true
      });
    }
    setError(null);
  }, [ticketType, isOpen]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      if (ticketType) {
        // Update existing ticket type
        const success = await updateTicketType(ticketType.id, formData);
        if (success) {
          onSave({ ...ticketType, ...formData });
          onClose();
        } else {
          setError('Failed to update ticket type');
        }
      } else {
        // Create new ticket type
        const newTicketType = await createTicketType(eventId, formData);
        if (newTicketType) {
          onSave(newTicketType);
          onClose();
        } else {
          setError('Failed to create ticket type');
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unexpected error occurred');
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? parseInt(value) || 0 : value
    }));
  };

  const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: checked
    }));
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 backdrop-blur-sm flex items-center justify-center p-4 z-50" style={{ background: 'rgba(0, 0, 0, 0.5)' }}>
      <div className="backdrop-blur-xl rounded-2xl shadow-2xl w-full max-w-md sm:max-w-lg max-h-[90vh] overflow-y-auto" style={{ background: 'var(--glass-bg-lg)', border: '1px solid var(--glass-border)' }}>
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-light" style={{ color: 'var(--glass-text-primary)' }}>
              {ticketType ? 'Edit Ticket Type' : 'Create Ticket Type'}
            </h2>
            <button
              onClick={onClose}
              className="transition-colors p-2 rounded-full touch-manipulation hover:opacity-80"
              style={{ color: 'var(--glass-text-tertiary)', background: 'var(--glass-bg-button)' }}
              aria-label="Close modal"
            >
              <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {error && (
            <div className="mb-4 p-3 rounded-lg" style={{ background: 'var(--error-bg)', border: '1px solid var(--error-border)', color: 'var(--error-color)' }}>
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="name" className="block text-sm font-medium mb-2" style={{ color: 'var(--glass-text-secondary)' }}>
                Ticket Name *
              </label>
              <input
                type="text"
                id="name"
                name="name"
                required
                value={formData.name}
                onChange={handleInputChange}
                className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="e.g., General Admission"
              />
            </div>

            <div>
              <label htmlFor="description" className="block text-sm font-medium text-white/80 mb-2">
                Description
              </label>
              <textarea
                id="description"
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                rows={3}
                className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                placeholder="Brief description of this ticket type..."
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="price_cents" className="block text-sm font-medium text-white/80 mb-2">
                  Price ($) *
                </label>
                <input
                  type="number"
                  id="price_cents"
                  name="price_cents"
                  required
                  min="0"
                  step="0.01"
                  value={formData.price_cents / 100}
                  onChange={(e) => {
                    const dollars = parseFloat(e.target.value) || 0;
                    setFormData(prev => ({
                      ...prev,
                      price_cents: Math.round(dollars * 100)
                    }));
                  }}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="0.00"
                />
              </div>

              <div>
                <label htmlFor="quantity" className="block text-sm font-medium text-white/80 mb-2">
                  Quantity *
                </label>
                <input
                  type="number"
                  id="quantity"
                  name="quantity"
                  required
                  min="1"
                  value={formData.quantity}
                  onChange={handleInputChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="100"
                />
              </div>
            </div>

            <div className="flex items-center">
              <input
                type="checkbox"
                id="is_active"
                name="is_active"
                checked={formData.is_active}
                onChange={handleCheckboxChange}
                className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500 focus:ring-2"
              />
              <label htmlFor="is_active" className="ml-2 text-sm text-white/80">
                Active (available for purchase)
              </label>
            </div>

            <div className="flex justify-end space-x-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="px-6 py-3 text-white/80 hover:text-white transition-colors"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={loading}
                className="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white rounded-lg font-medium transition-all duration-200 disabled:opacity-50"
              >
                {loading ? 'Saving...' : ticketType ? 'Update' : 'Create'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}