'use client'

import { useState, useEffect } from 'react'
import AuthModal from './AuthModal'

interface User {
  id: number
  username: string
  email: string
}

export default function Nav() {
  const [user, setUser] = useState<User | null>(null)
  const [showAuthModal, setShowAuthModal] = useState(false)
  const [loading, setLoading] = useState(true)
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)

  useEffect(() => {
    checkAuth()
  }, [])

  const checkAuth = async () => {
    try {
      const response = await fetch('/api/auth/session', {
        credentials: 'include',
      })
      if (response.ok) {
        const data = await response.json()
        setUser(data.user)
      }
    } catch (error) {
      console.error('Error checking auth:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleLogin = (loggedInUser: User) => {
    setUser(loggedInUser)
    setShowAuthModal(false)
  }

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', {
        method: 'POST',
        credentials: 'include',
      })
      setUser(null)
    } catch (error) {
      console.error('Error logging out:', error)
    }
  }

  return (
    <>
      <nav>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <div className="brand">
              <a href="/" style={{ display: 'inline-block', textDecoration: 'none' }}>
                <img src="/header.jpg" alt="420Deals.ch" style={{ height: '40px', width: 'auto' }} />
              </a>
            </div>
            <button
              className="mobile-menu-toggle"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              aria-label="Toggle menu"
            >
              <span style={{ display: mobileMenuOpen ? 'none' : 'block' }}>☰</span>
              <span style={{ display: mobileMenuOpen ? 'block' : 'none' }}>✕</span>
            </button>
          </div>
          <div className={`links ${mobileMenuOpen ? 'mobile-open' : ''}`}>
          <a href="#drop" onClick={() => setMobileMenuOpen(false)}>Drop</a>
          <a href="#past" onClick={() => setMobileMenuOpen(false)}>Past Drops</a>
          <a href="#community" onClick={() => setMobileMenuOpen(false)}>Community</a>
          {!loading && (
            user ? (
              <>
                <span style={{ color: 'var(--muted)', fontSize: '14px', marginLeft: '48px' }}>
                  {user.username}
                </span>
                <a
                  href="/orders"
                  onClick={() => setMobileMenuOpen(false)}
                  style={{
                    background: 'transparent',
                    border: '1px solid var(--border)',
                    color: 'var(--text)',
                    padding: '8px 16px',
                    borderRadius: '8px',
                    fontSize: '14px',
                    marginLeft: '12px',
                    lineHeight: '1',
                    boxSizing: 'border-box',
                    display: 'inline-block',
                    textDecoration: 'none',
                    cursor: 'pointer',
                  }}
                >
                  Orders
                </a>
                <button
                  onClick={() => {
                    handleLogout()
                    setMobileMenuOpen(false)
                  }}
                  style={{
                    background: 'transparent',
                    border: '1px solid #e57373',
                    color: '#e57373',
                    padding: '8px 16px',
                    borderRadius: '8px',
                    cursor: 'pointer',
                    fontSize: '14px',
                    marginLeft: '12px',
                    lineHeight: '1',
                    boxSizing: 'border-box',
                    display: 'inline-block',
                  }}
                >
                  Logout
                </button>
              </>
            ) : (
              <button
                onClick={() => {
                  setShowAuthModal(true)
                  setMobileMenuOpen(false)
                }}
                style={{
                  padding: '8px 16px',
                  fontSize: '14px',
                  background: '#0a7931',
                  color: '#fff',
                  border: 'none',
                  borderRadius: '8px',
                  cursor: 'pointer',
                  fontWeight: 500,
                  marginLeft: '48px',
                  lineHeight: '1',
                  boxSizing: 'border-box',
                  display: 'inline-block',
                }}
              >
                Login
              </button>
            )
          )}
          </div>
        </div>
      </nav>

      <AuthModal
        isOpen={showAuthModal}
        onClose={() => setShowAuthModal(false)}
        onLogin={handleLogin}
      />
    </>
  )
}

