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 [adminRole, setAdminRole] = useState(localStorage.getItem('adminRole'));
  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;
          const role = response.data.user?.role || 'admin';
          if (name) {
            setAdminName(name);
            setAdminRole(role);
            localStorage.setItem('adminName', name);
            localStorage.setItem('adminRole', role);
          } 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, role } = response.data;
      localStorage.setItem('adminToken', newToken);
      localStorage.setItem('adminName', name);
      localStorage.setItem('adminRole', role || 'admin');
      setToken(newToken);
      setAdminName(name);
      setAdminRole(role || 'admin');
      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');
    localStorage.removeItem('adminRole');
    setToken(null);
    setAdminName(null);
    setAdminRole(null);
    setIsAuthenticated(false);
  };

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

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