import { useState, useEffect } from 'react';
import { createClient } from '@supabase/supabase-js';
import { formatCurrency } from '../../lib/event-management';
import TicketPreviewModal from '../modals/TicketPreviewModal';

const supabase = createClient(
  import.meta.env.PUBLIC_SUPABASE_URL,
  import.meta.env.PUBLIC_SUPABASE_ANON_KEY
);

interface PrintedTicket {
  id: string;
  event_id: string;
  barcode: string;
  status: 'pending' | 'printed' | 'distributed' | 'used';
  notes: string;
  created_at: string;
  updated_at: string;
}

interface PrintedTabProps {
  eventId: string;
  organizationId: string;
}

export default function PrintedTab({ eventId, organizationId }: PrintedTabProps) {
  const [printedTickets, setPrintedTickets] = useState<PrintedTicket[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [barcodeMethod, setBarcodeMethod] = useState<'generate' | 'manual'>('generate');
  const [barcodeData, setBarcodeData] = useState({
    startNumber: 1,
    quantity: 100,
    prefix: 'BCT',
    padding: 6
  });
  const [manualBarcodes, setManualBarcodes] = useState('');
  const [editingTicket, setEditingTicket] = useState<PrintedTicket | null>(null);
  const [editForm, setEditForm] = useState({ status: 'pending', notes: '' });
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState(false);

  useEffect(() => {
    loadPrintedTickets();
  }, [eventId]);

  const loadPrintedTickets = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('printed_tickets')
        .select('*')
        .eq('event_id', eventId)
        .order('created_at', { ascending: false });

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

    } finally {
      setLoading(false);
    }
  };

  const generateBarcodes = (start: number, quantity: number, prefix: string, padding: number) => {
    const barcodes = [];
    for (let i = 0; i < quantity; i++) {
      const number = start + i;
      const paddedNumber = number.toString().padStart(padding, '0');
      barcodes.push(`${prefix}${paddedNumber}`);
    }
    return barcodes;
  };

  const handleCreateTickets = async () => {
    setProcessing(true);
    try {
      let barcodes: string[] = [];

      if (barcodeMethod === 'generate') {
        barcodes = generateBarcodes(
          barcodeData.startNumber,
          barcodeData.quantity,
          barcodeData.prefix,
          barcodeData.padding
        );
      } else {
        barcodes = manualBarcodes
          .split('\n')
          .map(line => line.trim())
          .filter(line => line.length > 0);
      }

      if (barcodes.length === 0) {
        alert('Please provide at least one barcode');
        return;
      }

      // Check for duplicate barcodes
      const existingBarcodes = printedTickets.map(ticket => ticket.barcode);
      const duplicates = barcodes.filter(barcode => existingBarcodes.includes(barcode));
      
      if (duplicates.length > 0) {
        alert(`Duplicate barcodes found: ${duplicates.join(', ')}`);
        return;
      }

      const ticketsToInsert = barcodes.map(barcode => ({
        event_id: eventId,
        barcode,
        status: 'pending' as const,
        notes: ''
      }));

      const { error } = await supabase
        .from('printed_tickets')
        .insert(ticketsToInsert);

      if (error) throw error;

      setShowModal(false);
      loadPrintedTickets();
      
      // Reset form
      setBarcodeData({
        startNumber: 1,
        quantity: 100,
        prefix: 'BCT',
        padding: 6
      });
      setManualBarcodes('');
    } catch (error) {

      alert('Failed to create printed tickets');
    } finally {
      setProcessing(false);
    }
  };

  const handleEditTicket = (ticket: PrintedTicket) => {
    setEditingTicket(ticket);
    setEditForm({
      status: ticket.status,
      notes: ticket.notes
    });
  };

  const handleUpdateTicket = async () => {
    if (!editingTicket) return;

    try {
      const { error } = await supabase
        .from('printed_tickets')
        .update({
          status: editForm.status,
          notes: editForm.notes
        })
        .eq('id', editingTicket.id);

      if (error) throw error;

      setEditingTicket(null);
      loadPrintedTickets();
    } catch (error) {

      alert('Failed to update printed ticket');
    }
  };

  const handleDeleteTicket = async (ticket: PrintedTicket) => {
    if (confirm(`Are you sure you want to delete the printed ticket "${ticket.barcode}"?`)) {
      try {
        const { error } = await supabase
          .from('printed_tickets')
          .delete()
          .eq('id', ticket.id);

        if (error) throw error;
        loadPrintedTickets();
      } catch (error) {

        alert('Failed to delete printed ticket');
      }
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30';
      case 'printed':
        return 'bg-blue-500/20 text-blue-300 border-blue-500/30';
      case 'distributed':
        return 'bg-green-500/20 text-green-300 border-green-500/30';
      case 'used':
        return 'bg-gray-500/20 text-gray-300 border-gray-500/30';
      default:
        return 'bg-white/20 text-white border-white/30';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'pending':
        return (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        );
      case 'printed':
        return (
          <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>
        );
      case 'distributed':
        return (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
          </svg>
        );
      case 'used':
        return (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        );
      default:
        return null;
    }
  };

  const getStatusStats = () => {
    const stats = {
      total: printedTickets.length,
      pending: printedTickets.filter(t => t.status === 'pending').length,
      printed: printedTickets.filter(t => t.status === 'printed').length,
      distributed: printedTickets.filter(t => t.status === 'distributed').length,
      used: printedTickets.filter(t => t.status === 'used').length
    };
    return stats;
  };

  const stats = getStatusStats();

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-light text-white mb-2">Printed Tickets</h2>
          <p className="text-white/80">Manage barcodes for printed tickets</p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => setShowPreviewModal(true)}
            className="bg-white/10 hover:bg-white/20 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 backdrop-blur-sm 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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
            </svg>
            Preview Sample Ticket
          </button>
          <button
            onClick={() => setShowModal(true)}
            className="px-6 py-3 rounded-xl font-medium transition-all duration-200 flex items-center gap-2"
            style={{
              background: 'var(--glass-text-accent)',
              color: 'white'
            }}
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            Add Printed Tickets
          </button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Total</div>
          <div className="text-2xl font-bold text-white">{stats.total}</div>
        </div>
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Pending</div>
          <div className="text-2xl font-bold text-yellow-400">{stats.pending}</div>
        </div>
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Printed</div>
          <div className="text-2xl font-bold text-blue-400">{stats.printed}</div>
        </div>
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Distributed</div>
          <div className="text-2xl font-bold text-green-400">{stats.distributed}</div>
        </div>
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Used</div>
          <div className="text-2xl font-bold text-gray-400">{stats.used}</div>
        </div>
      </div>

      {/* Tickets Table */}
      <div className="bg-white/5 border border-white/20 rounded-xl overflow-hidden">
        {printedTickets.length === 0 ? (
          <div className="text-center py-12">
            <svg className="w-12 h-12 text-white/40 mx-auto mb-4" 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-white/60 mb-4">No printed tickets created yet</p>
            <button
              onClick={() => setShowModal(true)}
              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"
            >
              Create Printed Tickets
            </button>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-white/10">
                <tr>
                  <th className="text-left py-3 px-4 text-white/80 font-medium">Barcode</th>
                  <th className="text-left py-3 px-4 text-white/80 font-medium">Status</th>
                  <th className="text-left py-3 px-4 text-white/80 font-medium">Notes</th>
                  <th className="text-left py-3 px-4 text-white/80 font-medium">Created</th>
                  <th className="text-left py-3 px-4 text-white/80 font-medium">Actions</th>
                </tr>
              </thead>
              <tbody>
                {printedTickets.map((ticket) => (
                  <tr key={ticket.id} className="border-b border-white/10 hover:bg-white/5 transition-colors">
                    <td className="py-3 px-4">
                      <div className="font-mono text-white">{ticket.barcode}</div>
                    </td>
                    <td className="py-3 px-4">
                      <span className={`flex items-center gap-2 px-2 py-1 text-xs rounded-full border ${getStatusColor(ticket.status)}`}>
                        {getStatusIcon(ticket.status)}
                        {ticket.status.charAt(0).toUpperCase() + ticket.status.slice(1)}
                      </span>
                    </td>
                    <td className="py-3 px-4">
                      <div className="text-white/80 text-sm">
                        {ticket.notes || '-'}
                      </div>
                    </td>
                    <td className="py-3 px-4">
                      <div className="text-white/80 text-sm">
                        {new Date(ticket.created_at).toLocaleDateString()}
                      </div>
                    </td>
                    <td className="py-3 px-4">
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => handleEditTicket(ticket)}
                          className="p-2 text-white/60 hover:text-white transition-colors"
                          title="Edit"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                          </svg>
                        </button>
                        <button
                          onClick={() => handleDeleteTicket(ticket)}
                          className="p-2 text-white/60 hover:text-red-400 transition-colors"
                          title="Delete"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Create Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl max-w-lg w-full">
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-2xl font-light text-white">Add Printed Tickets</h3>
                <button
                  onClick={() => setShowModal(false)}
                  className="text-white/60 hover:text-white transition-colors"
                >
                  <svg className="w-6 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="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-2">Input Method</label>
                  <div className="flex space-x-4">
                    <label className="flex items-center">
                      <input
                        type="radio"
                        value="generate"
                        checked={barcodeMethod === 'generate'}
                        onChange={(e) => setBarcodeMethod(e.target.value as 'generate' | 'manual')}
                        className="w-4 h-4 text-blue-600 bg-white/10 border-white/20"
                      />
                      <span className="ml-2 text-white text-sm">Generate Sequence</span>
                    </label>
                    <label className="flex items-center">
                      <input
                        type="radio"
                        value="manual"
                        checked={barcodeMethod === 'manual'}
                        onChange={(e) => setBarcodeMethod(e.target.value as 'generate' | 'manual')}
                        className="w-4 h-4 text-blue-600 bg-white/10 border-white/20"
                      />
                      <span className="ml-2 text-white text-sm">Manual Input</span>
                    </label>
                  </div>
                </div>

                {barcodeMethod === 'generate' ? (
                  <div className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-white/80 mb-2">Prefix</label>
                        <input
                          type="text"
                          value={barcodeData.prefix}
                          onChange={(e) => setBarcodeData(prev => ({ ...prev, prefix: e.target.value }))}
                          className="w-full px-3 py-2 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="BCT"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-white/80 mb-2">Padding</label>
                        <input
                          type="number"
                          value={barcodeData.padding}
                          onChange={(e) => setBarcodeData(prev => ({ ...prev, padding: parseInt(e.target.value) || 6 }))}
                          className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          min="1"
                          max="10"
                        />
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-white/80 mb-2">Start Number</label>
                        <input
                          type="number"
                          value={barcodeData.startNumber}
                          onChange={(e) => setBarcodeData(prev => ({ ...prev, startNumber: parseInt(e.target.value) || 1 }))}
                          className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          min="1"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-white/80 mb-2">Quantity</label>
                        <input
                          type="number"
                          value={barcodeData.quantity}
                          onChange={(e) => setBarcodeData(prev => ({ ...prev, quantity: parseInt(e.target.value) || 1 }))}
                          className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          min="1"
                          max="1000"
                        />
                      </div>
                    </div>
                    <div className="bg-white/5 border border-white/20 rounded-lg p-3">
                      <div className="text-sm text-white/60 mb-2">Preview:</div>
                      <div className="font-mono text-white text-sm">
                        {barcodeData.prefix}{barcodeData.startNumber.toString().padStart(barcodeData.padding, '0')} - {barcodeData.prefix}{(barcodeData.startNumber + barcodeData.quantity - 1).toString().padStart(barcodeData.padding, '0')}
                      </div>
                    </div>
                  </div>
                ) : (
                  <div>
                    <label className="block text-sm font-medium text-white/80 mb-2">Barcodes (one per line)</label>
                    <textarea
                      value={manualBarcodes}
                      onChange={(e) => setManualBarcodes(e.target.value)}
                      rows={8}
                      className="w-full px-3 py-2 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 font-mono"
                      placeholder="Enter barcodes, one per line&#10;Example:&#10;BCT000001&#10;BCT000002&#10;BCT000003"
                    />
                  </div>
                )}
              </div>

              <div className="flex justify-end space-x-3 mt-6">
                <button
                  onClick={() => setShowModal(false)}
                  className="px-6 py-3 text-white/80 hover:text-white transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleCreateTickets}
                  disabled={processing}
                  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"
                >
                  {processing ? 'Creating...' : 'Create Tickets'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Edit Modal */}
      {editingTicket && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl max-w-md w-full">
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-2xl font-light text-white">Edit Printed Ticket</h3>
                <button
                  onClick={() => setEditingTicket(null)}
                  className="text-white/60 hover:text-white transition-colors"
                >
                  <svg className="w-6 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="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-2">Barcode</label>
                  <div className="px-3 py-2 bg-white/5 border border-white/20 rounded-lg text-white font-mono">
                    {editingTicket.barcode}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-white/80 mb-2">Status</label>
                  <select
                    value={editForm.status}
                    onChange={(e) => setEditForm(prev => ({ ...prev, status: e.target.value as any }))}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="pending">Pending</option>
                    <option value="printed">Printed</option>
                    <option value="distributed">Distributed</option>
                    <option value="used">Used</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-white/80 mb-2">Notes</label>
                  <textarea
                    value={editForm.notes}
                    onChange={(e) => setEditForm(prev => ({ ...prev, notes: e.target.value }))}
                    rows={3}
                    className="w-full px-3 py-2 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="Optional notes..."
                  />
                </div>
              </div>

              <div className="flex justify-end space-x-3 mt-6">
                <button
                  onClick={() => setEditingTicket(null)}
                  className="px-6 py-3 text-white/80 hover:text-white transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleUpdateTicket}
                  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"
                >
                  Update
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Ticket Preview Modal */}
      <TicketPreviewModal
        isOpen={showPreviewModal}
        onClose={() => setShowPreviewModal(false)}
        eventId={eventId}
        organizationId={organizationId}
      />
    </div>
  );
}