import React, { useEffect } from 'react';
import { useServerActions } from '../../../hooks/useServerActions';
import { usePluginContext } from '../../../context/PluginContext/usePluginContext';
import Button from '../../common/Button/Button';
import ScanProgress from '../ScanProgress/ScanProgress';
import './ServerSelector.css';

export const ServerSelector: React.FC = () => {
  const {
    serverPath,
    isScanning,
    scanComplete,
    scanProgress,
    error,
    selectDirectory,
    scanForPlugins,
    lastScanResult
  } = useServerActions();

  const { setPlugins } = usePluginContext();

  // Effect to handle scan results
  useEffect(() => {
    if (lastScanResult && lastScanResult.plugins) {
      console.log("Setting plugins from lastScanResult in ServerSelector");
      setPlugins(lastScanResult.plugins);
    }
  }, [lastScanResult, setPlugins]);

  const handleSelectDirectory = async () => {
    await selectDirectory();
  };

  const handleScanForPlugins = async () => {
    await scanForPlugins();
  };

  const handleResetSelection = () => {
    // Clear server path and plugins
    setPlugins([]);
  };

  return (
    <div className="server-selector">
      <div className="server-actions">
        <Button
          onClick={handleSelectDirectory}
          disabled={isScanning}
          variant="primary"
          tooltip="Choose the root folder of your Minecraft server"
        >
          Select Server Directory
        </Button>

        {serverPath && !isScanning && (
          <Button
            onClick={handleScanForPlugins}
            disabled={!serverPath || isScanning}
            isLoading={isScanning}
            variant="success"
            tooltip="Scan the selected server directory for plugins"
          >
            Scan for Plugins
          </Button>
        )}

        {serverPath && scanComplete && (
          <Button
            onClick={handleResetSelection}
            disabled={isScanning}
            variant="secondary"
            tooltip="Clear the current server selection and plugin list"
          >
            Reset
          </Button>
        )}
      </div>

      {isScanning && (
        <>
          {/* Add debug info */}
          <div style={{ display: 'none' }}>
            <pre>Debug - scanProgress: {JSON.stringify(scanProgress, null, 2)}</pre>
          </div>
          <ScanProgress progress={scanProgress} />
        </>
      )}

      {error && (
        <div className="server-selector-error">
          <p className="error-message" role="alert">Error: {error}</p>
        </div>
      )}
    </div>
  );
};

export default ServerSelector;