import { useState, useEffect } from 'react';
import { makeAuthenticatedRequest } from '../../lib/api-client';

interface EventsTabProps {
  platformMetrics: Record<string, unknown> | null;
  user: { id: string; email: string } | null;
}

export default function EventsTab({ _platformMetrics, _user }: EventsTabProps) {
  const [activeSection, setActiveSection] = useState('events');
  const [loading, setLoading] = useState(false);
  const [events, setEvents] = useState<Record<string, unknown>[]>([]);
  const [tickets, setTickets] = useState<Record<string, unknown>[]>([]);
  const [ticketStats, setTicketStats] = useState<Record<string, unknown> | null>(null);
  const [_filters, _setFilters] = useState<Record<string, unknown>>({});

  useEffect(() => {
    if (activeSection === 'events') {
      loadEvents();
    } else {
      loadTickets();
    }
  }, [activeSection]);

  const loadEvents = async () => {
    setLoading(true);
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=event_analytics');
      if (result.success) {
        setEvents(result.data.events || []);
      }
    } catch (error) {
      console.error('Events loading error:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadTickets = async () => {
    setLoading(true);
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=ticket_analytics&limit=50');
      if (result.success) {
        setTickets(result.data.tickets || []);
        setTicketStats(result.data.stats || {});
      }
    } catch (error) {
      console.error('Tickets loading error:', error);
    } finally {
      setLoading(false);
    }
  };

  const editEvent = (eventId: string) => {
    window.open(`/events/${eventId}/manage`, '_blank');
  };

  const viewOrganizerDashboard = (organizationId: string) => {
    window.open(`/admin/organizer-view/${organizationId}`, '_blank');
  };

  const _deleteEvent = (_eventId: string) => {
    if (confirm('Are you sure you want to delete this event? This action cannot be undone.')) {

      // Implement event deletion API call
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'status-pill status-success';
      case 'used': return 'status-pill status-info';
      case 'refunded': return 'status-pill status-error';
      case 'cancelled': return 'status-pill status-neutral';
      default: return 'status-pill status-neutral';
    }
  };

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

  return (
    <div className="p-4 md:p-6 space-y-6">
      <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
        <h3 className="text-xl md:text-2xl font-light text-white">Events & Tickets Management</h3>
        
        {/* Section Toggle */}
        <div className="flex items-center bg-white/10 rounded-lg p-1">
          <button
            onClick={() => setActiveSection('events')}
            className={`px-3 py-1 rounded-lg text-sm transition-all ${
              activeSection === 'events' 
                ? 'bg-white/20 text-white' 
                : 'text-white/60 hover:text-white'
            }`}
          >
            Events
          </button>
          <button
            onClick={() => setActiveSection('tickets')}
            className={`px-3 py-1 rounded-lg text-sm transition-all ${
              activeSection === 'tickets' 
                ? 'bg-white/20 text-white' 
                : 'text-white/60 hover:text-white'
            }`}
          >
            Tickets
          </button>
        </div>
      </div>

      {activeSection === 'events' ? (
        <div className="space-y-6">
          {/* Events Actions */}
          <div className="flex flex-col sm:flex-row gap-3">
            <button
              onClick={() => window.open('/events/new', '_blank')}
              className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white rounded-lg text-sm font-medium transition-all"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              Create Event
            </button>
            <button
              onClick={loadEvents}
              className="flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 border border-white/20 rounded-lg text-white text-sm transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              Refresh
            </button>
          </div>

          {/* Events Table */}
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full min-w-[700px]">
                <thead className="bg-white/10 backdrop-blur-xl">
                  <tr>
                    <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Event</th>
                    <th className="text-left p-3 md:p-4 text-white font-medium text-sm hidden md:table-cell">Organizer</th>
                    <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Date</th>
                    <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Revenue</th>
                    <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Tickets</th>
                    <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/10">
                  {events.map(event => {
                    const eventDate = new Date(event.startTime);
                    const _isPast = eventDate < new Date();
                    
                    return (
                      <tr key={event.id} className="hover:bg-white/10">
                        <td className="p-3 md:p-4">
                          <div className="text-white font-medium text-sm">{event.title}</div>
                          <div className="text-white/60 text-xs">{event.sellThroughRate?.toFixed(1) || 0}% sold</div>
                          <div className="md:hidden text-white/60 text-xs mt-1">{event.organizerName || 'Unknown'}</div>
                        </td>
                        <td className="p-3 md:p-4 text-white/80 text-sm hidden md:table-cell">{event.organizerName || 'Unknown'}</td>
                        <td className="p-3 md:p-4 text-white/80 text-sm">
                          <div>{eventDate.toLocaleDateString()}</div>
                          <div className="text-xs text-white/60">{eventDate.toLocaleTimeString()}</div>
                        </td>
                        <td className="p-3 md:p-4 text-white/80 text-sm">${(event.totalRevenue || 0).toLocaleString()}</td>
                        <td className="p-3 md:p-4 text-white/80 text-sm">{event.ticketsSold || 0}</td>
                        <td className="p-3 md:p-4">
                          <div className="flex flex-col sm:flex-row gap-1">
                            <button
                              onClick={() => editEvent(event.id)}
                              className="bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white px-2 py-1 rounded text-xs"
                            >
                              Edit
                            </button>
                            <button
                              onClick={() => viewOrganizerDashboard(event.organizationId)}
                              className="bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white px-2 py-1 rounded text-xs"
                            >
                              Org
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                  {events.length === 0 && (
                    <tr>
                      <td colSpan={6} className="p-4 text-white/60 text-center">No events found</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      ) : (
        <div className="space-y-6">
          {/* Ticket Stats */}
          {ticketStats && (
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4">
              <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-3 md:p-4">
                <div className="text-xs md:text-sm text-white/60">Total</div>
                <div className="text-lg md:text-2xl font-bold text-white">{ticketStats.total || 0}</div>
              </div>
              <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-3 md:p-4">
                <div className="text-xs md:text-sm text-white/60">Active</div>
                <div className="text-lg md:text-2xl font-bold" style={{ color: 'var(--success-color)' }}>{ticketStats.active || 0}</div>
              </div>
              <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-3 md:p-4">
                <div className="text-xs md:text-sm text-white/60">Used</div>
                <div className="text-lg md:text-2xl font-bold" style={{ color: 'var(--glass-text-accent)' }}>{ticketStats.used || 0}</div>
              </div>
              <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-3 md:p-4">
                <div className="text-xs md:text-sm text-white/60">Refunded</div>
                <div className="text-lg md:text-2xl font-bold" style={{ color: 'var(--error-color)' }}>{ticketStats.refunded || 0}</div>
              </div>
            </div>
          )}

          {/* Tickets Actions */}
          <div className="flex flex-col sm:flex-row gap-3">
            <button
              onClick={loadTickets}
              className="flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 border border-white/20 rounded-lg text-white text-sm transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              Refresh Tickets
            </button>
          </div>

          {/* Tickets Table */}
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full min-w-[600px]">
                <thead className="bg-white/5">
                  <tr>
                    <th className="text-left p-3 text-white font-medium text-sm">Customer</th>
                    <th className="text-left p-3 text-white font-medium text-sm hidden md:table-cell">Event</th>
                    <th className="text-left p-3 text-white font-medium text-sm">Price</th>
                    <th className="text-left p-3 text-white font-medium text-sm">Status</th>
                    <th className="text-left p-3 text-white font-medium text-sm">Date</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/10">
                  {tickets.map((ticket, index) => (
                    <tr key={ticket.id || index} className="hover:bg-white/10">
                      <td className="p-3">
                        <div className="text-white font-medium text-sm">{ticket.customerName || 'N/A'}</div>
                        <div className="text-white/60 text-xs">{ticket.customerEmail || 'N/A'}</div>
                        <div className="md:hidden text-white/60 text-xs mt-1">{ticket.event?.title || 'N/A'}</div>
                      </td>
                      <td className="p-3 hidden md:table-cell">
                        <div className="text-white font-medium text-sm">{ticket.event?.title || 'N/A'}</div>
                        <div className="text-white/60 text-xs">{ticket.event?.organizationName || 'N/A'}</div>
                      </td>
                      <td className="p-3 text-white/80 text-sm">${(ticket.price || 0).toFixed(2)}</td>
                      <td className="p-3">
                        <span className={`px-2 py-1 rounded-full text-xs ${getStatusColor(ticket.status || 'unknown')}`}>
                          {(ticket.status || 'unknown').charAt(0).toUpperCase() + (ticket.status || 'unknown').slice(1)}
                        </span>
                      </td>
                      <td className="p-3 text-white/80 text-xs">
                        {ticket.createdAt ? new Date(ticket.createdAt).toLocaleDateString() : 'N/A'}
                      </td>
                    </tr>
                  ))}
                  {tickets.length === 0 && (
                    <tr>
                      <td colSpan={5} className="p-4 text-white/60 text-center">No tickets found</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}