import React, { useState, useEffect } from 'react'
import Login from './pages/Login'
import Register from './pages/Register'
import ProfileEditor from './pages/ProfileEditor'
import Discover from './pages/Discover'
import Matches from './pages/Matches'
import Chat from './pages/Chat'
import Modal from './components/Modal'
import LikesModal from './components/LikesModal'
import ProfilePhotoModal from './components/ProfilePhotoModal'
import { likeAPI, chatAPI, profileAPI, API_BASE_URL } from './api'
import logo from './assets/icons/logo.png'
import logoutIcon from './assets/icons/logout.svg'
import discoverIcon from './assets/icons/discover.svg'
import chatIcon from './assets/icons/chat.svg'
import matchesIcon from './assets/icons/matches.svg'
import likeIcon from './assets/icons/likes.svg'
import lightModeIcon from './assets/icons/lightMode.svg'
import darkModeIcon from './assets/icons/darkMode.svg'
import './App.css'

function App() {
  const [currentPage, setCurrentPage] = useState('login')
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [notificationData, setNotificationData] = useState({ unreadMessages: 0, likesReceived: 0 })
  const [showLogoutModal, setShowLogoutModal] = useState(false)
  const [showLikesModal, setShowLikesModal] = useState(false)
  const [showProfilePhotoModal, setShowProfilePhotoModal] = useState(false)
  const [userProfile, setUserProfile] = useState(null)
  const [isDarkMode, setIsDarkMode] = useState(() => {
    const saved = localStorage.getItem('darkMode')
    const isDark = saved === null ? true : saved === 'true'
    // Set theme immediately on init
    document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light')
    return isDark
  })
  const [isRefreshing, setIsRefreshing] = useState(false)

  useEffect(() => {
    const token = localStorage.getItem('token')
    const savedPage = localStorage.getItem('currentPage')
    if (token) {
      setIsAuthenticated(true)
      setCurrentPage(savedPage || 'discover')
      loadUserProfile()
    }
  }, [])

  useEffect(() => {
    // Set theme whenever isDarkMode changes
    document.documentElement.setAttribute('data-theme', isDarkMode ? 'dark' : 'light')
    localStorage.setItem('darkMode', isDarkMode ? 'true' : 'false')
  }, [isDarkMode])

  useEffect(() => {
    if (isAuthenticated && currentPage !== 'login' && currentPage !== 'register') {
      localStorage.setItem('currentPage', currentPage)
    }
  }, [currentPage, isAuthenticated])

  const loadUserProfile = async () => {
    try {
      const response = await profileAPI.getMyProfile()
      setUserProfile(response.data)
    } catch (err) {
      console.error('Failed to load user profile', err)
    }
  }

  useEffect(() => {
    if (isAuthenticated) {
      loadNotifications()
      // Refresh notifications every 5 seconds
      const interval = setInterval(loadNotifications, 5000)
      return () => clearInterval(interval)
    }
  }, [isAuthenticated])

  const loadNotifications = async () => {
    try {
      const [messagesRes, likesRes] = await Promise.all([
        chatAPI.getConversations(),
        likeAPI.getLikesReceived(),
      ])
      
      const unreadMessages = messagesRes.data?.reduce((sum, conv) => sum + (conv.unread_count || 0), 0) || 0
      const likesReceived = likesRes.data?.length || 0
      
      setNotificationData({
        unreadMessages,
        likesReceived,
      })
    } catch (err) {
      console.error('Failed to load notifications', err)
    }
  }

  const handleLoginSuccess = () => {
    setIsAuthenticated(true)
    setCurrentPage('discover')
    loadUserProfile()
  }

  const handleRegisterSuccess = () => {
    setIsAuthenticated(true)
    setCurrentPage('profile-editor')
    loadUserProfile()
  }

  const confirmLogout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('user_id')
    setIsAuthenticated(false)
    setCurrentPage('login')
    setShowLogoutModal(false)
    setUserProfile(null)
  }

  const handleRefresh = async () => {
    setIsRefreshing(true)
    try {
      await Promise.all([loadNotifications(), loadUserProfile()])
    } finally {
      setIsRefreshing(false)
    }
  }

  const toggleTheme = () => {
    setIsDarkMode(!isDarkMode)
  }

  const userPhoto = userProfile?.photos && userProfile.photos.length > 0 
    ? `${API_BASE_URL}/media/${userProfile.photos[0].file_path}`
    : null

  return (
    <div className="app">
      {isAuthenticated && (
        <nav className="navbar">
          <div className="nav-brand">
            <img src={logo} alt="Dating App Logo" className="nav-logo" />
            <span>Dating App</span>
          </div>
          <div className="nav-links">
            <button 
              onClick={() => setCurrentPage('discover')}
              className="nav-icon-btn"
              title="Discover profiles"
            >
              <img src={discoverIcon} alt="Discover" className="discover-icon" />
            </button>
            <button 
              onClick={() => setCurrentPage('matches')}
              className="nav-icon-btn"
              title="Your matches"
            >
              <img src={matchesIcon} alt="Matches" className="matches-icon" />
            </button>
            <button 
              onClick={() => setCurrentPage('chat')} 
              className="nav-icon-btn nav-btn-with-badge"
              title="Chat"
            >
              <img src={chatIcon} alt="Chat" className="chat-icon" />
              {notificationData.unreadMessages > 0 && (
                <span className="notification-badge" title="Unread messages">
                  {notificationData.unreadMessages}
                </span>
              )}
            </button>
            <button 
              onClick={() => setShowLikesModal(true)} 
              className="nav-icon-btn nav-btn-with-badge"
              title="Likes received"
            >
              <img src={likeIcon} alt="Likes" className="like-icon" />
              {notificationData.likesReceived > 0 && (
                <span className="notification-badge likes-badge" title="New likes">
                  {notificationData.likesReceived}
                </span>
              )}
            </button>
            <div className="nav-profile" onClick={() => setShowProfilePhotoModal(true)}>
              {userPhoto ? (
                <img 
                  src={userPhoto} 
                  alt="Your profile" 
                  className="nav-profile-pic"
                  title="Click to update your profile photo"
                />
              ) : (
                <div className="nav-profile-pic-placeholder">
                  {userProfile?.display_name?.charAt(0).toUpperCase()}
                </div>
              )}
            </div>
            <button 
              onClick={handleRefresh}
              className={`nav-icon-btn ${isRefreshing ? 'rotating' : ''}`}
              title="Refresh"
              disabled={isRefreshing}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="23 4 23 10 17 10"></polyline>
                <polyline points="1 20 1 14 7 14"></polyline>
                <path d="M3.51 9a9 9 0 0 1 14.85-3.36M20.49 15a9 9 0 0 1-14.85 3.36"></path>
              </svg>
            </button>
            <button 
              onClick={toggleTheme}
              className="nav-icon-btn"
              title={isDarkMode ? 'Light mode' : 'Dark mode'}
            >
              <img src={isDarkMode ? lightModeIcon : darkModeIcon} alt="Theme" className="theme-icon" />
            </button>
            <button 
              onClick={() => setShowLogoutModal(true)}
              className="nav-icon-btn nav-logout-btn"
              title="Logout"
            >
              <img src={logoutIcon} alt="Logout" className="logout-icon" />
              <span className="logout-text">Logout</span>
            </button>
          </div>
        </nav>
      )}

      <main className="main-content">
        {isAuthenticated && currentPage === 'discover' && userProfile && (
          <div className="greeting-banner">
            <h2>Welcome back, {userProfile.display_name}! 👋</h2>
            <p>Ready to find your perfect match?</p>
          </div>
        )}
        {currentPage === 'login' && (
          <Login onLoginSuccess={handleLoginSuccess} onRegisterClick={() => setCurrentPage('register')} />
        )}
        {currentPage === 'register' && (
          <Register onRegisterSuccess={handleRegisterSuccess} onLoginClick={() => setCurrentPage('login')} />
        )}
        {isAuthenticated && currentPage === 'profile-editor' && <ProfileEditor />}
        {isAuthenticated && currentPage === 'discover' && <Discover onNotificationsUpdate={loadNotifications} onNavigateToChat={() => setCurrentPage('chat')} />}
        {isAuthenticated && currentPage === 'matches' && <Matches onNavigateToChat={() => setCurrentPage('chat')} />}
        {isAuthenticated && currentPage === 'chat' && <Chat onNotificationsUpdate={loadNotifications} />}
      </main>

      <Modal
        isOpen={showLogoutModal}
        title="Confirm Logout"
        message="Are you sure you want to logout? You can login again anytime."
        confirmText="Yes, Logout"
        cancelText="Cancel"
        isDangerous={true}
        onConfirm={confirmLogout}
        onCancel={() => setShowLogoutModal(false)}
      />

      <LikesModal
        isOpen={showLikesModal}
        onClose={() => setShowLikesModal(false)}
        onLikesUpdate={loadNotifications}
      />

      <ProfilePhotoModal
        isOpen={showProfilePhotoModal}
        onClose={() => setShowProfilePhotoModal(false)}
        currentPhoto={userPhoto?.replace(`${API_BASE_URL}/media/`, '')}
        onPhotoUpdate={() => loadUserProfile()}
        onEditProfile={() => setCurrentPage('profile-editor')}
      />
    </div>
  )
}

export default App
