import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import {
  getSetupStatus,
  createInitialAdmin,
  login as loginRequest,
  logout as logoutRequest,
  fetchCsrfToken,
  clearStoredCsrfToken
} from '../services/adminApi';

const AdminSessionContext = createContext(null);

export const AdminSessionProvider = ({ children }) => {
  const [loading, setLoading] = useState(true);
  const [needsSetup, setNeedsSetup] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  const refreshStatus = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const status = await getSetupStatus();
      setNeedsSetup(Boolean(status.needsSetup));
      setIsAuthenticated(Boolean(status.hasSession));
      setUser(status.user || null);
      if (status.hasSession) {
        try {
          await fetchCsrfToken();
        } catch (csrfError) {
          console.warn('[AdminSession] CSRF refresh failed', csrfError);
        }
      }
    } catch (statusError) {
      console.error('[AdminSession] setup status failed', statusError);
      setError(statusError);
      setNeedsSetup(false);
      setIsAuthenticated(false);
      setUser(null);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleLogin = useCallback(async (credentials) => {
    const result = await loginRequest(credentials);
    setIsAuthenticated(true);
    setNeedsSetup(false);
    setUser(result.user || null);
    return result;
  }, []);

  const handleInitialAdmin = useCallback(async (payload) => {
    const result = await createInitialAdmin(payload);
    setIsAuthenticated(true);
    setNeedsSetup(false);
    setUser(result.user || null);
    return result;
  }, []);

  const handleLogout = useCallback(async () => {
    await logoutRequest();
    clearStoredCsrfToken();
    setIsAuthenticated(false);
    setUser(null);
  }, []);

  const value = useMemo(() => ({
    loading,
    needsSetup,
    isAuthenticated,
    user,
    error,
    refreshStatus,
    login: handleLogin,
    logout: handleLogout,
    createInitialAdmin: handleInitialAdmin
  }), [loading, needsSetup, isAuthenticated, user, error, refreshStatus, handleLogin, handleLogout, handleInitialAdmin]);

  return (
    <AdminSessionContext.Provider value={value}>
      {children}
    </AdminSessionContext.Provider>
  );
};

export const useAdminSession = () => {
  const context = useContext(AdminSessionContext);
  if (!context) {
    throw new Error('useAdminSession must be used within AdminSessionProvider');
  }
  return context;
};
