import React, {useEffect, useState} from 'react';
import {APIProvider, useAPI} from './providers/APIProvider';
import {LoadTestProvider} from './providers/LoadTestProvider';
import DialogManager from '@/components/shared/DialogManager';
import {monacoConfig} from '@/config/monaco.js';
import LoginDialog from '@/components/account/LoginDialog.jsx';
import AppMenu from './components/app-menu/AppMenu';
import {SCREENS} from './config/screenConfig';

window.MonacoEnvironment = monacoConfig;

const App = ({options = {contextPath: '/'}}) => {
  const [showLogin, setShowLogin] = useState(false);

  return (
      <APIProvider contextPath={options.contextPath}>
        <AppContent options={options} showLogin={showLogin} setShowLogin={setShowLogin}/>
      </APIProvider>
  );
};

const AppContent = ({options, showLogin, setShowLogin}) => {
  const {isAuthenticated, setIsAuthenticated, handleLogout} = useAPI();
  const [isInitialized, setIsInitialized] = useState(false);
  const [currentScreen, setCurrentScreen] = useState('api-tester');
  const [dialogState, setDialogState] = useState({
    showAddApi: false,
    showAddCollection: false,
    showAddScenario: false,
    showVariableModal: false,
    showMockRouteEdit: false,
    showTCPServerEdit: false,
    showQueueEdit: false,
    showUserEdit: false,
    showPasswordChange: false,
    showServerEdit: false,
    selectedItem: null
  });

  const handleMenuClick = async (action, screen, item = null) => {

    console.log(action);
    console.log(item);

    if (screen) {
      console.log('Screen:', screen);
      setCurrentScreen(screen);
      return;
    }

    // Handle modal actions
    switch (action) {
      case 'request-add':
        setDialogState(prev => ({...prev, showAddApi: true}));
        break;
      case 'response-add':
      case 'response-edit':
      case 'response-clone':
        setDialogState(prev => ({...prev, showMockRouteEdit: true, selectedItem: item}));
        break;
      case 'queue-add':
      case 'queue-edit':
        setDialogState(prev => ({...prev, showQueueEdit: true, selectedItem: item}));
        break;
      case 'user-add':
      case 'user-edit':
        setDialogState(prev => ({...prev, showUserEdit: true, selectedItem: item}));
        break;
      case 'socket-add':
      case 'socket-edit':
        setDialogState(prev => ({...prev, showTCPServerEdit: true, selectedItem: item}));
        break;
      case 'server-add':
      case 'server-edit':
        setDialogState(prev => ({...prev, showServerEdit: true, selectedItem: item}));
        break;
      case 'collection-add':
        setDialogState(prev => ({...prev, showAddCollection: true}));
        break;
      case 'scenario-add':
        setDialogState(prev => ({...prev, showAddScenario: true}));
        break;
      case 'variables-show':
        setDialogState(prev => ({...prev, showVariableModal: true}));
        break;
      case 'change-password':
        setDialogState(prev => ({...prev, showPasswordChange: true}));
        break;
      case 'logout':
        const success = await handleLogout();
        if (success) {
          window.location.href = `${options.contextPath}/actionLogout.do`;
        }
        break;
    }
  };

  const checkAuth = async () => {
    try {
      const response = await fetch('/api/account', {});

      if (response.status !== 200) {
        setShowLogin(true);
        setIsAuthenticated(false);
        return;
      }

      const data = await response.json();
      setIsAuthenticated(!!data.authorities);
      if (!data.authorities) {
        setShowLogin(true);
      }
    } catch (error) {
      console.error('Auth check failed:', error);
      setShowLogin(true);
      setIsAuthenticated(false);
    }
  };

  useEffect(() => {
    if (!isInitialized) {
      setIsInitialized(true);
      checkAuth();
    }
  }, [isInitialized, checkAuth]);

  const handleDialogChange = (dialogName, isOpen) => {
    setDialogState(prev => ({...prev, [dialogName]: isOpen}));
  };

  if (!isAuthenticated) {
    return <LoginDialog open={showLogin} onOpenChange={setShowLogin}/>;
  }

  const CurrentScreenComponent = SCREENS[currentScreen] || SCREENS['api-tester'];

  return (
      <LoadTestProvider contextPath={options.contextPath}>
        <div className="flex flex-col h-screen bg-background">
          <AppMenu onMenuClick={handleMenuClick}/>
          <DialogManager
              showAddApi={dialogState.showAddApi}
              showAddCollection={dialogState.showAddCollection}
              showAddScenario={dialogState.showAddScenario}
              showVariableModal={dialogState.showVariableModal}
              showMockRouteEdit={dialogState.showMockRouteEdit}
              showTCPServerEdit={dialogState.showTCPServerEdit}
              showQueueEdit={dialogState.showQueueEdit}
              showUserEdit={dialogState.showUserEdit}
              selectedItem={dialogState.selectedItem}
              showPasswordChange={dialogState.showPasswordChange}
              showServerEdit={dialogState.showServerEdit}
              onDialogChange={handleDialogChange}
          />
          <div className="flex-1 mt-14">
            <CurrentScreenComponent onMenuClick={handleMenuClick}/>
          </div>
        </div>
      </LoadTestProvider>
  );
};

export default App;
