import React, { createContext, useContext, useState, useEffect } from 'react';
import { Box, CircularProgress, Typography } from '@mui/material';
import { apiFetch, getErrorMessage } from '../lib/api';
import { logger } from '../lib/logger';

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

interface AuthContextType {
  isAuthenticated: boolean;
  user: User | null;
  loading: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState<boolean>(true);

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

  const checkAuth = async () => {
    logger.debug('Checking authentication...');
    try {
      const response = await apiFetch('/auth/me', { method: 'GET' });

      if (response.ok) {
        const userData = await response.json();
        logger.debug('User authenticated:', userData.username);
        setUser(userData);
        setIsAuthenticated(true);
      } else {
        logger.debug('Not authenticated:', response.status);
        setUser(null);
        setIsAuthenticated(false);
      }
    } catch (error) {
      logger.error('Auth check failed:', error);
      setUser(null);
      setIsAuthenticated(false);
    } finally {
      setLoading(false);
      logger.debug('Auth check complete');
    }
  };

  const login = async (username: string, password: string) => {
    const response = await apiFetch('/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password }),
    });

    if (!response.ok) {
      throw new Error(await getErrorMessage(response, 'Login failed'));
    }

    const data = await response.json();
    setUser(data.user);
    setIsAuthenticated(true);
  };

  const logout = async () => {
    await apiFetch('/auth/logout', {
      method: 'POST',
    });
    setUser(null);
    setIsAuthenticated(false);
  };

  if (loading) {
    return (
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          minHeight: '100vh',
          backgroundColor: '#f8fafc',
          gap: 2,
        }}
      >
        <CircularProgress size={48} />
        <Typography variant="body2" color="textSecondary">
          Loading...
        </Typography>
      </Box>
    );
  }

  return (
    <AuthContext.Provider value={{ isAuthenticated, user, loading, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};
