import { useState, useEffect } from 'react'
import EventList from './components/EventList'
import EventForm from './components/EventForm'
import TemplateEditor from './components/TemplateEditor'
import EventMembers from './components/EventMembers'
import GuestList from './components/GuestList'
import GuestSelfService from './components/GuestSelfService'
import Login from './components/Login'
import ThemeToggle from './components/ThemeToggle'
import './App.css'

function App() {
  const [currentPage, setCurrentPage] = useState('events')  // 'events', 'guests', 'guest-self-service', 'templates'
  const [selectedEventId, setSelectedEventId] = useState(null)
  const [showEventForm, setShowEventForm] = useState(false)
  const [showMembersModal, setShowMembersModal] = useState(false)
  // rsvpEventId: UUID from /guest/:eventId route (new flow)
  const [rsvpEventId, setRsvpEventId] = useState(null)
  // Check if user is authenticated by looking for userId in localStorage
  const [isAuthenticated, setIsAuthenticated] = useState(() => {
    return !!localStorage.getItem('userId')
  })
  const [theme, setTheme] = useState(() => {
    return localStorage.getItem('theme') || 'light'
  })

  // Initialize theme
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('theme', theme)
  }, [theme])

  // Listen for authentication changes (when user logs in via Google)
  useEffect(() => {
    const handleStorageChange = () => {
      setIsAuthenticated(!!localStorage.getItem('userId'))
    }

    // Check if just logged in via Google OAuth callback
    if (localStorage.getItem('userId') && !isAuthenticated) {
      setIsAuthenticated(true)
    }

    // Listen for changes in other tabs
    window.addEventListener('storage', handleStorageChange)
    return () => window.removeEventListener('storage', handleStorageChange)
  }, [isAuthenticated])

  // Check URL for current page/event and restore from URL params
  useEffect(() => {
    const path = window.location.pathname
    const params = new URLSearchParams(window.location.search)

    // Handle guest RSVP page with event ID in path: /guest/:eventId
    // This is the new flow — event_id is the WhatsApp button URL suffix
    const guestEventMatch = path.match(/^\/guest\/([a-f0-9-]{36})\/?$/i)
    if (guestEventMatch) {
      setRsvpEventId(guestEventMatch[1])
      setCurrentPage('guest-self-service')
      return
    }

    // Handle guest self-service mode — also check ?event= query param (sent in WhatsApp body text)
    if (path === '/guest' || path === '/guest/') {
      // Try to extract event ID from ?event=<uuid> or ?event_id=<uuid> query param
      const eventFromQuery =
        params.get('event') || params.get('event_id') || null
      setRsvpEventId(eventFromQuery)
      setCurrentPage('guest-self-service')
      return
    }

    // Handle guests page with eventId in URL: /events/:eventId/guests
    const match = path.match(/^\/events\/([^/]+)\/guests\/?$/)
    if (match) {
      const eventIdFromUrl = match[1]
      setSelectedEventId(eventIdFromUrl)
      setCurrentPage('guests')
      return
    }

    // Handle OAuth callback - either in query params or sessionStorage
    const eventIdFromUrl = params.get('eventId')
    const googleEventId = sessionStorage.getItem('googleEventId')
    const eventToNavigateTo = eventIdFromUrl || googleEventId

    if (eventToNavigateTo) {
      setSelectedEventId(eventToNavigateTo)
      setCurrentPage('guests')
      // Navigate to proper URL format
      window.history.replaceState({}, document.title, `/events/${eventToNavigateTo}/guests`)
      // Clean up sessionStorage
      sessionStorage.removeItem('googleEventId')
      return
    }

    // Default to events page
    setCurrentPage('events')
  }, [])

  const handleGoToTemplates = () => setCurrentPage('templates')
  const handleBackFromTemplates = () => setCurrentPage('events')

  const handleEventSelect = (eventId) => {
    setSelectedEventId(eventId)
    setCurrentPage('guests')
    // Navigate to proper URL format
    window.history.pushState({}, document.title, `/events/${eventId}/guests`)
  }

  const handleBackToEvents = () => {
    setSelectedEventId(null)
    setCurrentPage('events')
    window.history.pushState({}, document.title, '/')
  }

  const handleEventCreated = (newEvent) => {
    setShowEventForm(false)
    setSelectedEventId(newEvent.id)
    setCurrentPage('guests')
    window.history.pushState({}, document.title, `/events/${newEvent.id}/guests`)
  }

  const toggleTheme = () => {
    setTheme(theme === 'light' ? 'dark' : 'light')
  }

  if (!isAuthenticated && currentPage !== 'guest-self-service') {
    return <Login onLogin={() => setIsAuthenticated(true)} />
  }

  return (
    <div className="app" dir="rtl">
      <ThemeToggle theme={theme} onToggle={toggleTheme} />
      {currentPage === 'events' && (
        <>
          <EventList 
            onEventSelect={handleEventSelect}
            onCreateEvent={() => setShowEventForm(true)}
            onManageTemplates={handleGoToTemplates}
          />
          {showEventForm && (
            <EventForm 
              onEventCreated={handleEventCreated}
              onCancel={() => setShowEventForm(false)}
            />
          )}
        </>
      )}

      {currentPage === 'guests' && selectedEventId && (
        <>
          <GuestList 
            eventId={selectedEventId}
            onBack={handleBackToEvents}
            onShowMembers={() => setShowMembersModal(true)}
          />
          {showMembersModal && (
            <EventMembers 
              eventId={selectedEventId}
              onClose={() => setShowMembersModal(false)}
            />
          )}
        </>
      )}

      {currentPage === 'templates' && (
        <TemplateEditor onBack={handleBackFromTemplates} />
      )}

      {currentPage === 'guest-self-service' && (
        <GuestSelfService eventId={rsvpEventId} />
      )}
    </div>
  )
}

export default App
