'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)

  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 className="brand">
          <a href="/" style={{ display: 'inline-block', textDecoration: 'none' }}>
            <img src="/header.jpg" alt="420Deals.ch" style={{ height: '40px', width: 'auto' }} />
          </a>
        </div>
        <div className="links">
          <a href="#drop">Drop</a>
          <a href="#past">Past Drops</a>
          <a href="#community">Community</a>
          {!loading && (
            user ? (
              <>
                <span style={{ color: 'var(--muted)', fontSize: '14px', marginLeft: '48px' }}>
                  {user.username}
                </span>
                <button
                  onClick={handleLogout}
                  style={{
                    background: 'transparent',
                    border: '1px solid var(--border)',
                    color: 'var(--text)',
                    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)}
                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>
      </nav>

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

