import React, { createContext, useState, useContext, useEffect } from 'react';
import axios from 'axios';
import { migratePreferences } from '../utils/adminPrefs';

const AuthContext = createContext();

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

export const AuthProvider = ({ children }) => {
  const [token, setToken] = useState(localStorage.getItem('adminToken'));
  const [adminName, setAdminName] = useState(localStorage.getItem('adminName'));
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const verifyToken = async () => {
      if (token) {
        try {
          const response = await axios.post('/api/auth/verify', {}, {
            headers: { Authorization: `Bearer ${token}` }
          });
          setIsAuthenticated(true);
          const name = response.data.user?.name;
          if (name) {
            setAdminName(name);
            localStorage.setItem('adminName', name);
          } else {
            logout();
          }
        } catch (error) {
          console.error('Token verification failed:', error);
          logout();
        }
      }
      setLoading(false);
    };

    verifyToken();
  }, [token]);

  const login = async (key) => {
    try {
      const response = await axios.post('/api/auth/login', { key });
      const { token: newToken, name } = response.data;
      localStorage.setItem('adminToken', newToken);
      localStorage.setItem('adminName', name);
      setToken(newToken);
      setAdminName(name);
      setIsAuthenticated(true);
      migratePreferences(name);
      return { success: true };
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.error || 'Login failed'
      };
    }
  };

  const logout = () => {
    localStorage.removeItem('adminToken');
    localStorage.removeItem('adminName');
    setToken(null);
    setAdminName(null);
    setIsAuthenticated(false);
  };

  const value = {
    token,
    adminName,
    isAuthenticated,
    loading,
    login,
    logout
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
