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

interface TicketPreviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  eventId: string;
  organizationId: string;
}

interface TicketType {
  id: string;
  name: string;
  price: number;
}

interface PreviewData {
  eventTitle: string;
  eventDate: string;
  eventTime: string;
  venue: string;
  ticketType: string;
  price: string;
  barcode: string;
}

export default function TicketPreviewModal({ isOpen, onClose, eventId, organizationId }: TicketPreviewModalProps) {
  const [ticketTypes, setTicketTypes] = useState<TicketType[]>([]);
  const [selectedTicketType, setSelectedTicketType] = useState('');
  const [previewData, setPreviewData] = useState<PreviewData | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      loadTicketTypes();
    }
  }, [isOpen, eventId]);

  const loadTicketTypes = async () => {
    try {
      const { data, error } = await supabase
        .from('ticket_types')
        .select('id, name, price')
        .eq('event_id', eventId)
        .eq('is_active', true)
        .order('display_order');

      if (error) throw error;
      setTicketTypes(data || []);
    } catch (error) {

    }
  };

  const generateTicketPreview = async (ticketTypeId: string) => {
    if (!ticketTypeId) {
      setPreviewData(null);
      return;
    }

    setLoading(true);
    try {
      // Load event details
      const { data: event } = await supabase
        .from('events')
        .select('title, date, venue')
        .eq('id', eventId)
        .single();

      const ticketType = ticketTypes.find(t => t.id === ticketTypeId);
      
      if (event && ticketType) {
        const eventDate = new Date(event.date);
        setPreviewData({
          eventTitle: event.title,
          eventDate: eventDate.toLocaleDateString('en-US', { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric' 
          }),
          eventTime: eventDate.toLocaleTimeString('en-US', {
            hour: 'numeric',
            minute: '2-digit'
          }),
          venue: event.venue,
          ticketType: ticketType.name,
          price: `$${(ticketType.price / 100).toFixed(2)}`,
          barcode: 'SAMPLE-' + Math.random().toString(36).substr(2, 9).toUpperCase()
        });
      }
    } catch (error) {

    } finally {
      setLoading(false);
    }
  };

  const handlePrint = () => {
    const printContent = document.getElementById('ticket-preview-content');
    if (!printContent) return;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
      <html>
        <head>
          <title>Sample Ticket</title>
          <style>
            body { font-family: Arial, sans-serif; margin: 20px; }
            .ticket-wrapper { max-width: 400px; margin: 0 auto; }
            @media print {
              body { margin: 0; }
              .ticket-wrapper { max-width: none; }
            }
          </style>
        </head>
        <body>
          ${printContent.innerHTML}
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50" onClick={onClose}>
      <div className="flex items-center justify-center min-h-screen p-4">
        <div 
          className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-3xl shadow-2xl w-full max-w-sm sm:max-w-2xl lg:max-w-4xl max-h-[90vh] overflow-y-auto"
          onClick={(e) => e.stopPropagation()}
        >
          <div className="p-4 sm:p-6 lg:p-8">
            <div className="flex justify-between items-center mb-6 sm:mb-8">
              <div>
                <h2 className="text-xl sm:text-2xl lg:text-3xl font-light text-white mb-2">Sample Ticket Preview</h2>
                <p className="text-sm sm:text-base text-white/80">Preview how your printed tickets will look</p>
              </div>
              <button
                onClick={onClose}
                className="text-white/60 hover:text-white transition-colors duration-200 p-2 rounded-full hover:bg-white/10 touch-manipulation"
                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>
            
            <div className="bg-white/5 backdrop-blur-sm rounded-2xl p-4 sm:p-6 mb-6">
              <div className="flex flex-col sm:flex-row gap-4 mb-6">
                <select
                  value={selectedTicketType}
                  onChange={(e) => {
                    setSelectedTicketType(e.target.value);
                    generateTicketPreview(e.target.value);
                  }}
                  className="bg-white/10 border border-white/20 text-white px-4 py-2 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">Select ticket type...</option>
                  {ticketTypes.map(type => (
                    <option key={type.id} value={type.id}>
                      {type.name} - ${(type.price / 100).toFixed(2)}
                    </option>
                  ))}
                </select>
                <button
                  onClick={handlePrint}
                  disabled={!previewData}
                  className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 disabled:from-gray-600 disabled:to-gray-600 text-white px-6 py-2 rounded-xl font-medium transition-all duration-200 flex items-center gap-2"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                  </svg>
                  Print Sample
                </button>
              </div>
              
              <div id="ticket-preview-content" className="bg-white rounded-2xl p-8 relative min-h-[400px] flex items-center justify-center">
                {loading ? (
                  <div className="text-gray-500 text-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-500 mx-auto mb-4"></div>
                    <p className="text-lg font-medium">Generating preview...</p>
                  </div>
                ) : previewData ? (
                  <div className="ticket-wrapper relative">
                    {/* SAMPLE Watermark */}
                    <div className="absolute inset-0 flex items-center justify-center pointer-events-none z-10">
                      <div className="text-red-300 text-8xl font-bold opacity-40 transform rotate-45 select-none">
                        SAMPLE
                      </div>
                    </div>
                    
                    {/* Ticket Content */}
                    <div className="bg-white border-2 border-gray-300 rounded-lg shadow-lg p-6 max-w-md mx-auto relative">
                      <div className="text-center mb-4">
                        <h3 className="text-2xl font-bold text-gray-900 mb-2">{previewData.eventTitle}</h3>
                        <p className="text-gray-700 font-medium">{previewData.eventDate}</p>
                        <p className="text-gray-700 font-medium">{previewData.eventTime}</p>
                      </div>
                      
                      <div className="border-t border-b border-gray-300 py-4 mb-4">
                        <p className="text-gray-600 text-sm uppercase tracking-wide mb-1">Venue</p>
                        <p className="text-gray-900 font-semibold">{previewData.venue}</p>
                      </div>
                      
                      <div className="grid grid-cols-2 gap-4 mb-4">
                        <div>
                          <p className="text-gray-600 text-sm uppercase tracking-wide mb-1">Ticket Type</p>
                          <p className="text-gray-900 font-semibold">{previewData.ticketType}</p>
                        </div>
                        <div className="text-right">
                          <p className="text-gray-600 text-sm uppercase tracking-wide mb-1">Price</p>
                          <p className="text-gray-900 font-semibold">{previewData.price}</p>
                        </div>
                      </div>
                      
                      <div className="bg-gray-100 rounded-lg p-4 text-center">
                        <div className="bg-black text-white font-mono text-sm py-2 px-4 rounded mb-2">
                          {previewData.barcode}
                        </div>
                        <div className="flex justify-center">
                          <svg className="h-12" viewBox="0 0 200 50">
                            {[...Array(40)].map((_, i) => (
                              <rect
                                key={i}
                                x={i * 5}
                                y="0"
                                width={Math.random() > 0.5 ? 3 : 2}
                                height="50"
                                fill="#000"
                              />
                            ))}
                          </svg>
                        </div>
                      </div>
                      
                      <p className="text-center text-gray-500 text-xs mt-4">
                        This is a sample ticket for preview purposes only
                      </p>
                    </div>
                  </div>
                ) : (
                  <div className="text-gray-500 text-center">
                    <svg className="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
                    </svg>
                    <p className="text-lg font-medium mb-2">Select a ticket type to preview</p>
                    <p className="text-sm opacity-75">The preview will show how your ticket will look when printed</p>
                  </div>
                )}
              </div>
            </div>
            
            <div className="flex justify-end">
              <button
                onClick={onClose}
                className="px-6 py-3 rounded-xl font-medium text-white/80 hover:text-white transition-colors duration-200"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}