'use client';

import { useEffect, useState, useCallback } from 'react';
import { apiClient, hasStoredToken } from '@/lib/api';
import type { UserAccount } from '@/types';

const AUTH_ME_TIMEOUT_MS = 60000; // 60s for /auth/me (backend may be slow or cold)

export default function Header() {
  const [currentUser, setCurrentUser] = useState<UserAccount | null>(null);
  const [connectionError, setConnectionError] = useState<'timeout' | 'network' | null>(null);

  const checkAuth = useCallback(async () => {
    if (typeof window === 'undefined') return;
    if (!hasStoredToken()) {
      window.location.href = '/login';
      return;
    }
    setConnectionError(null);
    try {
      const { data } = await apiClient.get<UserAccount>('/auth/me', {
        timeout: AUTH_ME_TIMEOUT_MS,
      });
      setCurrentUser(data);
    } catch (error: any) {
      if (error?.message === 'No access token' || error?.response?.status === 401) {
        window.location.href = '/login';
        return;
      }
      const isTimeout =
        error?.code === 'ECONNABORTED' ||
        (error?.message && String(error.message).toLowerCase().includes('timeout'));
      const isNetworkError =
        error?.code === 'ERR_NETWORK' ||
        (error?.message && String(error.message) === 'Network Error');
      if (isTimeout) {
        setConnectionError('timeout');
        return;
      }
      if (isNetworkError) {
        setConnectionError('network');
        return;
      }
      console.error('Auth error:', error);
    }
  }, []);

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

  return (
    <header className="top-header">
      <div className="header-content">
        <h1 className="header-title">Boundary Commission</h1>
        <p style={{ color: 'var(--text-muted)', marginTop: '5px' }}>
          Boundary Commission Digital Archive System
        </p>
      </div>
      <div className="user-info">
        <div className="user-avatar">
          {currentUser ? (currentUser.full_name || currentUser.username || 'U').charAt(0).toUpperCase() : 'U'}
        </div>
        <div>
          <div style={{ fontWeight: 600 }}>
            {currentUser
              ? currentUser.full_name || currentUser.username
              : connectionError
                ? (connectionError === 'timeout' ? 'Connection timeout' : 'Network error')
                : 'Loading...'}
          </div>
          <div style={{ fontSize: '0.85em', color: 'var(--text-muted)' }}>
            {currentUser
              ? (currentUser.is_super_admin
                  ? 'Super Admin'
                  : currentUser.is_admin
                    ? 'Admin'
                    : currentUser.primary_role ||
                      (currentUser.roles && currentUser.roles.length > 0 ? currentUser.roles[0] : 'User'))
              : connectionError ? (
                <button
                  type="button"
                  onClick={checkAuth}
                  style={{
                    background: 'none',
                    border: 'none',
                    color: 'var(--primary, #2563eb)',
                    cursor: 'pointer',
                    padding: 0,
                    textDecoration: 'underline',
                  }}
                >
                  Retry
                </button>
              ) : (
                'User'
              )}
          </div>
        </div>
      </div>
    </header>
  );
}
