import { useState, useEffect } from 'react';
import TabNavigation from './manage/TabNavigation';
import TicketingAccessTab from './manage/TicketingAccessTab';
import OrdersTab from './manage/OrdersTab';
import AttendeesTab from './manage/AttendeesTab';
import EventSettingsTab from './manage/EventSettingsTab';
import CustomPageTab from './manage/CustomPageTab';
import { api } from '../lib/api-router.js';
import type { EventData } from '../lib/event-management.js';

interface EventManagementProps {
  eventId: string;
  organizationId?: string;
  eventSlug?: string;
}

export default function EventManagement({ eventId, _organizationId, eventSlug }: EventManagementProps) {
  const [activeTab, setActiveTab] = useState('ticketing');
  const [eventData, setEventData] = useState<EventData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [_user, setUser] = useState<unknown>(null);
  const [userOrganizationId, setUserOrganizationId] = useState<string | null>(null);
  const [actualEventSlug, setActualEventSlug] = useState<string | null>(eventSlug || null);

  const tabs = [
    {
      id: 'ticketing',
      name: 'Ticketing & Access',
      icon: (
        <svg className="w-5 h-5" 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>
      ),
      component: TicketingAccessTab
    },
    {
      id: 'custom-pages',
      name: 'Custom Pages',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
        </svg>
      ),
      component: CustomPageTab
    },
    {
      id: 'sales',
      name: 'Sales',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
        </svg>
      ),
      component: OrdersTab
    },
    {
      id: 'attendees',
      name: 'Attendees',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
        </svg>
      ),
      component: AttendeesTab
    },
    {
      id: 'settings',
      name: 'Event Settings',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      ),
      component: EventSettingsTab
    }
  ];

  useEffect(() => {
    // Check authentication and load data
    const initializeComponent = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // Check authentication status
        const authStatus = await api.checkAuth();
        
        if (!authStatus.authenticated) {
          // Give a bit more time for auth to load on page refresh
          // Auth check failed, retrying in 1 second...
          setTimeout(async () => {
            const retryAuthStatus = await api.checkAuth();
            if (!retryAuthStatus.authenticated) {
              // Still not authenticated, redirect to login
              // Auth retry failed, redirecting to login
              window.location.href = '/login';
              return;
            }
            // Retry loading with successful auth
            // Auth retry succeeded, reinitializing component
            initializeComponent();
          }, 1000);
          return;
        }
        
        setUser(authStatus.user);
        
        if (!authStatus.organizationId) {
          setError('User not associated with any organization');
          return;
        }
        
        setUserOrganizationId(authStatus.organizationId);
        
        // Load event data using centralized API
        const data = await api.loadEventData(eventId);
        if (data) {
          setEventData(data);
          setActualEventSlug(data.slug);
        } else {
          setError(`Event not found or access denied. Event ID: ${eventId}`);
        }
      } catch (err) {
        console.error('EventManagement initialization error:', err);
        setError('Failed to load event data. Please try again.');
      } finally {
        setLoading(false);
      }
    };

    initializeComponent();
  }, [eventId]);

  // Loading state
  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-2 mx-auto mb-4" style={{borderColor: 'var(--glass-text-primary)', borderTopColor: 'transparent'}}></div>
          <p style={{color: 'var(--glass-text-secondary)'}}>Loading event data...</p>
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="w-12 h-12 rounded-xl flex items-center justify-center mx-auto mb-4" style={{background: 'var(--error-bg)'}}>
            <svg className="w-6 h-6" style={{color: 'var(--error-color)'}} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <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>
          </div>
          <p className="font-medium mb-2" style={{color: 'var(--error-color)'}}>Error Loading Event</p>
          <p className="text-sm mb-4" style={{color: 'var(--glass-text-secondary)'}}>{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 border rounded-lg text-sm transition-colors backdrop-blur-lg"
            style={{
              background: 'var(--ui-bg-elevated)',
              borderColor: 'var(--ui-border-primary)',
              color: 'var(--ui-text-primary)'
            }}
            onMouseEnter={(e) => e.target.style.background = 'var(--ui-bg-secondary)'}
            onMouseLeave={(e) => e.target.style.background = 'var(--ui-bg-elevated)'}
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <TabNavigation
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={setActiveTab}
      eventId={eventId}
      organizationId={userOrganizationId || ''}
      eventData={eventData}
      eventSlug={actualEventSlug}
    />
  );
}