'use client'

import { useState, useEffect } from 'react'
import Image from 'next/image'
import AuthModal from './AuthModal'
import RedeemPointsModal from './RedeemPointsModal'
import LanguageSwitcher from './LanguageSwitcher'
import { useI18n } from '@/lib/i18n'

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

export default function Nav() {
  const { t } = useI18n()
  const [user, setUser] = useState<User | null>(null)
  const [showAuthModal, setShowAuthModal] = useState(false)
  const [showRedeemModal, setShowRedeemModal] = 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()
        const userData = data.user
        
        // If user is logged in, fetch referral points
        if (userData) {
          try {
            const pointsResponse = await fetch('/api/referral-points', {
              credentials: 'include',
            })
            if (pointsResponse.ok) {
              const pointsData = await pointsResponse.json()
              userData.referral_points = pointsData.referral_points
            }
          } catch (error) {
            console.error('Error fetching referral points:', error)
          }
        }
        
        setUser(userData)
      }
    } 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)
    }
  }

  const handleRedeemSuccess = async () => {
    // Refresh points after successful redemption
    if (user) {
      try {
        const pointsResponse = await fetch('/api/referral-points', {
          credentials: 'include',
        })
        if (pointsResponse.ok) {
          const pointsData = await pointsResponse.json()
          setUser({ ...user, referral_points: pointsData.referral_points })
        }
      } catch (error) {
        console.error('Error fetching referral points:', 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.png" alt="420Deals.ch" style={{ height: '50px', 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)}>{t('nav.drop')}</a>
          <a href="#past" onClick={() => setMobileMenuOpen(false)}>{t('nav.pastDrops')}</a>
          <a href="#community" onClick={() => setMobileMenuOpen(false)}>{t('nav.community')}</a>
          <LanguageSwitcher />
          {!loading && (
            user ? (
              <>
                <span style={{ color: 'var(--muted)', fontSize: '14px', marginLeft: '48px' }}>
                  {user.username}
                </span>
                {user.referral_points !== undefined && user.referral_points > 0 && (
                  <>
                    <span style={{ 
                      color: '#0a7931', 
                      fontSize: '14px', 
                      marginLeft: '12px',
                      fontWeight: 500,
                      display: 'flex',
                      alignItems: 'center',
                      gap: '6px',
                    }}>
                      <Image 
                        src="/icon_ref_points.png" 
                        alt="Referral Points" 
                        width={16} 
                        height={16}
                        style={{ display: 'inline-block', verticalAlign: 'middle' }}
                      />
                      {user.referral_points.toFixed(0)} pts
                    </span>
                    <button
                      onClick={() => {
                        setShowRedeemModal(true)
                        setMobileMenuOpen(false)
                      }}
                      style={{
                        background: 'transparent',
                        border: '1px solid #0a7931',
                        color: '#0a7931',
                        padding: '8px 16px',
                        borderRadius: '8px',
                        fontSize: '14px',
                        marginLeft: '12px',
                        lineHeight: '1',
                        boxSizing: 'border-box',
                        display: 'inline-block',
                        cursor: 'pointer',
                        fontWeight: 500,
                      }}
                    >
                      {t('redeemPoints.redeem')}
                    </button>
                  </>
                )}
                <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',
                  }}
                >
                  {t('nav.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',
                  }}
                >
                  {t('nav.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',
                }}
              >
                {t('nav.login')}
              </button>
            )
          )}
          </div>
        </div>
      </nav>

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

      {user && user.referral_points !== undefined && (
        <RedeemPointsModal
          isOpen={showRedeemModal}
          onClose={() => setShowRedeemModal(false)}
          currentPoints={user.referral_points}
          onRedeemSuccess={handleRedeemSuccess}
        />
      )}
    </>
  )
}

