import { useState, useEffect } from 'react';
import { Core, Scene } from '@esengine/ecs-framework';
import { EditorPluginManager, UIRegistry, MessageHub, SerializerRegistry, EntityStoreService, ComponentRegistry, LocaleService, ProjectService, ComponentDiscoveryService, ComponentLoaderService, PropertyMetadataService, LogService } from '@esengine/editor-core';
import { SceneInspectorPlugin } from './plugins/SceneInspectorPlugin';
import { StartupPage } from './components/StartupPage';
import { SceneHierarchy } from './components/SceneHierarchy';
import { EntityInspector } from './components/EntityInspector';
import { AssetBrowser } from './components/AssetBrowser';
import { ConsolePanel } from './components/ConsolePanel';
import { DockContainer, DockablePanel } from './components/DockContainer';
import { TauriAPI } from './api/tauri';
import { useLocale } from './hooks/useLocale';
import { en, zh } from './locales';
import { Plus, Trash2, Loader2, Globe } from 'lucide-react';
import './styles/App.css';

const coreInstance = Core.create({ debug: true });

const localeService = new LocaleService();
localeService.registerTranslations('en', en);
localeService.registerTranslations('zh', zh);
Core.services.registerInstance(LocaleService, localeService);

function App() {
  const [initialized, setInitialized] = useState(false);
  const [projectLoaded, setProjectLoaded] = useState(false);
  const [currentProjectPath, setCurrentProjectPath] = useState<string | null>(null);
  const [pluginManager, setPluginManager] = useState<EditorPluginManager | null>(null);
  const [entityStore, setEntityStore] = useState<EntityStoreService | null>(null);
  const [messageHub, setMessageHub] = useState<MessageHub | null>(null);
  const [logService, setLogService] = useState<LogService | null>(null);
  const { t, locale, changeLocale } = useLocale();
  const [status, setStatus] = useState(t('header.status.initializing'));
  const [panels, setPanels] = useState<DockablePanel[]>([]);

  useEffect(() => {
    const initializeEditor = async () => {
      try {
        (window as any).__ECS_FRAMEWORK__ = await import('@esengine/ecs-framework');

        const editorScene = new Scene();
        Core.setScene(editorScene);

        const uiRegistry = new UIRegistry();
        const messageHub = new MessageHub();
        const serializerRegistry = new SerializerRegistry();
        const entityStore = new EntityStoreService(messageHub);
        const componentRegistry = new ComponentRegistry();
        const projectService = new ProjectService(messageHub);
        const componentDiscovery = new ComponentDiscoveryService(messageHub);
        const componentLoader = new ComponentLoaderService(messageHub, componentRegistry);
        const propertyMetadata = new PropertyMetadataService();
        const logService = new LogService();

        Core.services.registerInstance(UIRegistry, uiRegistry);
        Core.services.registerInstance(MessageHub, messageHub);
        Core.services.registerInstance(SerializerRegistry, serializerRegistry);
        Core.services.registerInstance(EntityStoreService, entityStore);
        Core.services.registerInstance(ComponentRegistry, componentRegistry);
        Core.services.registerInstance(ProjectService, projectService);
        Core.services.registerInstance(ComponentDiscoveryService, componentDiscovery);
        Core.services.registerInstance(ComponentLoaderService, componentLoader);
        Core.services.registerInstance(PropertyMetadataService, propertyMetadata);
        Core.services.registerInstance(LogService, logService);

        const pluginMgr = new EditorPluginManager();
        pluginMgr.initialize(coreInstance, Core.services);

        await pluginMgr.installEditor(new SceneInspectorPlugin());

        const greeting = await TauriAPI.greet('Developer');
        console.log(greeting);

        setInitialized(true);
        setPluginManager(pluginMgr);
        setEntityStore(entityStore);
        setMessageHub(messageHub);
        setLogService(logService);
        setStatus(t('header.status.ready'));
      } catch (error) {
        console.error('Failed to initialize editor:', error);
        setStatus(t('header.status.failed'));
      }
    };

    initializeEditor();
  }, []);

  const handleOpenProject = async () => {
    try {
      const projectPath = await TauriAPI.openProjectDialog();
      if (!projectPath) return;

      const projectService = Core.services.resolve(ProjectService);
      const discoveryService = Core.services.resolve(ComponentDiscoveryService);
      const loaderService = Core.services.resolve(ComponentLoaderService);

      if (!projectService || !discoveryService || !loaderService) {
        console.error('Required services not available');
        return;
      }

      await projectService.openProject(projectPath);

      await fetch('/@user-project-set-path', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ path: projectPath })
      });

      setStatus('Scanning components...');

      const componentsPath = projectService.getComponentsPath();
      if (componentsPath) {
        const componentInfos = await discoveryService.scanComponents({
          basePath: componentsPath,
          pattern: '**/*.ts',
          scanFunction: TauriAPI.scanDirectory,
          readFunction: TauriAPI.readFileContent
        });

        setStatus(`Loading ${componentInfos.length} components...`);

        const modulePathTransform = (filePath: string) => {
          const relativePath = filePath.replace(projectPath, '').replace(/\\/g, '/');
          return `/@user-project${relativePath}`;
        };

        await loaderService.loadComponents(componentInfos, modulePathTransform);

        setStatus(t('header.status.projectOpened') + ` (${componentInfos.length} components registered)`);
      } else {
        setStatus(t('header.status.projectOpened'));
      }

      setCurrentProjectPath(projectPath);
      setProjectLoaded(true);
    } catch (error) {
      console.error('Failed to open project:', error);
      setStatus(t('header.status.failed'));
    }
  };

  const handleCreateProject = async () => {
    console.log('Create project not implemented yet');
  };

  const handleCreateEntity = () => {
    if (!initialized || !entityStore) return;
    const scene = Core.scene;
    if (!scene) return;

    const entity = scene.createEntity('Entity');
    entityStore.addEntity(entity);
  };

  const handleDeleteEntity = () => {
    if (!entityStore) return;
    const selected = entityStore.getSelectedEntity();
    if (selected) {
      selected.destroy();
      entityStore.removeEntity(selected);
    }
  };

  const handleLocaleChange = () => {
    const newLocale = locale === 'en' ? 'zh' : 'en';
    changeLocale(newLocale);
  };

  useEffect(() => {
    if (projectLoaded && entityStore && messageHub && logService) {
      setPanels([
        {
          id: 'scene-hierarchy',
          title: locale === 'zh' ? '场景层级' : 'Scene Hierarchy',
          position: 'left',
          content: <SceneHierarchy entityStore={entityStore} messageHub={messageHub} />,
          closable: false
        },
        {
          id: 'inspector',
          title: locale === 'zh' ? '检视器' : 'Inspector',
          position: 'right',
          content: <EntityInspector entityStore={entityStore} messageHub={messageHub} />,
          closable: false
        },
        {
          id: 'viewport',
          title: locale === 'zh' ? '视口' : 'Viewport',
          position: 'center',
          content: (
            <div className="viewport">
              <h3>{t('viewport.title')}</h3>
              <p>{t('viewport.placeholder')}</p>
            </div>
          ),
          closable: false
        },
        {
          id: 'assets',
          title: locale === 'zh' ? '资产' : 'Assets',
          position: 'bottom',
          content: <AssetBrowser projectPath={currentProjectPath} locale={locale} />,
          closable: false
        },
        {
          id: 'console',
          title: locale === 'zh' ? '控制台' : 'Console',
          position: 'bottom',
          content: <ConsolePanel logService={logService} />,
          closable: false
        }
      ]);
    }
  }, [projectLoaded, entityStore, messageHub, logService, locale, currentProjectPath, t]);

  const handlePanelMove = (panelId: string, newPosition: any) => {
    setPanels(prevPanels =>
      prevPanels.map(panel =>
        panel.id === panelId ? { ...panel, position: newPosition } : panel
      )
    );
  };

  if (!initialized) {
    return (
      <div className="editor-loading">
        <Loader2 size={32} className="animate-spin" />
        <h2>Loading Editor...</h2>
      </div>
    );
  }

  if (!projectLoaded) {
    return (
      <StartupPage
        onOpenProject={handleOpenProject}
        onCreateProject={handleCreateProject}
        recentProjects={[]}
        locale={locale}
      />
    );
  }

  return (
    <div className="editor-container">
      <div className="editor-header">
        <h1>{t('app.title')}</h1>
        <div className="header-toolbar">
          <button onClick={handleCreateEntity} disabled={!initialized} className="toolbar-btn">
            <Plus size={14} />
            {t('header.toolbar.createEntity')}
          </button>
          <button onClick={handleDeleteEntity} disabled={!entityStore?.getSelectedEntity()} className="toolbar-btn">
            <Trash2 size={14} />
            {t('header.toolbar.deleteEntity')}
          </button>
          <button onClick={handleLocaleChange} className="toolbar-btn locale-btn" title={locale === 'en' ? '切换到中文' : 'Switch to English'}>
            <Globe size={14} />
          </button>
        </div>
        <span className="status">{status}</span>
      </div>

      <div className="editor-content">
        <DockContainer panels={panels} onPanelMove={handlePanelMove} />
      </div>

      <div className="editor-footer">
        <span>{t('footer.plugins')}: {pluginManager?.getAllEditorPlugins().length ?? 0}</span>
        <span>{t('footer.entities')}: {entityStore?.getAllEntities().length ?? 0}</span>
        <span>{t('footer.core')}: {initialized ? t('footer.active') : t('footer.inactive')}</span>
      </div>
    </div>
  );
}

export default App;
