import { useEffect, useState } from 'react';
import { DockviewReact, DockviewReadyEvent, IDockviewPanelProps } from 'dockview';
import { TaskDock } from './docks/TaskDock';
import { PropertiesDock } from './docks/PropertiesDock';
import { ConsoleDock } from './docks/ConsoleDock';
import { FileExplorerDock } from './docks/FileExplorerDock';
import { Box } from '@mantine/core';
import 'dockview/dist/styles/dockview.css';
import './dockview.css';

// Contexto para comunicación entre docks
interface DockCommunicationContext {
  selectedFile: any;
  properties: any;
  tasks: any[];
  logs: any[];
  updateSelectedFile: (file: any) => void;
  updateProperties: (props: any) => void;
  updateTasks: (tasks: any[]) => void;
  addLog: (log: any) => void;
}

const dockCommunication: DockCommunicationContext = {
  selectedFile: null,
  properties: null,
  tasks: [],
  logs: [],
  updateSelectedFile: () => {},
  updateProperties: () => {},
  updateTasks: () => {},
  addLog: () => {},
};

// Componentes wrapper para cada dock
const TaskDockWrapper = (props: IDockviewPanelProps) => {
  return (
    <TaskDock
      onTaskUpdate={(tasks) => {
        dockCommunication.updateTasks(tasks);
        dockCommunication.addLog({
          id: Date.now().toString(),
          timestamp: new Date(),
          level: 'info',
          message: `Tareas actualizadas: ${tasks.length} tareas en total`
        });
      }}
    />
  );
};

const PropertiesDockWrapper = (props: IDockviewPanelProps) => {
  return (
    <PropertiesDock
      onPropertiesChange={(properties) => {
        dockCommunication.updateProperties(properties);
        dockCommunication.addLog({
          id: Date.now().toString(),
          timestamp: new Date(),
          level: 'success',
          message: `Propiedades actualizadas para: ${properties.name}`
        });
      }}
    />
  );
};

const ConsoleDockWrapper = (props: IDockviewPanelProps) => {
  return (
    <ConsoleDock
      onLogAdd={(log) => {
        dockCommunication.addLog(log);
      }}
    />
  );
};

const FileExplorerDockWrapper = (props: IDockviewPanelProps) => {
  return (
    <FileExplorerDock
      onFileSelect={(file) => {
        dockCommunication.updateSelectedFile(file);
        dockCommunication.addLog({
          id: Date.now().toString(),
          timestamp: new Date(),
          level: 'info',
          message: `Archivo seleccionado: ${file.label}`
        });
      }}
    />
  );
};

export function DockViewMain() {
  const [api, setApi] = useState<DockviewReadyEvent>();

  // Estados para comunicación entre docks
  const [selectedFile, setSelectedFile] = useState<any>(null);
  const [properties, setProperties] = useState<any>(null);
  const [tasks, setTasks] = useState<any[]>([]);
  const [logs, setLogs] = useState<any[]>([]);

  // Actualizar el contexto de comunicación
  useEffect(() => {
    dockCommunication.selectedFile = selectedFile;
    dockCommunication.properties = properties;
    dockCommunication.tasks = tasks;
    dockCommunication.logs = logs;
    dockCommunication.updateSelectedFile = setSelectedFile;
    dockCommunication.updateProperties = setProperties;
    dockCommunication.updateTasks = setTasks;
    dockCommunication.addLog = (log) => setLogs(prev => [log, ...prev]);
  }, [selectedFile, properties, tasks, logs]);

  const onReady = (event: DockviewReadyEvent) => {
    setApi(event);

    // Configurar el layout inicial
    const panel1 = event.api.addPanel({
      id: 'file-explorer',
      component: 'fileExplorer',
      title: 'Explorador',
    });

    const panel2 = event.api.addPanel({
      id: 'properties',
      component: 'properties',
      title: 'Propiedades',
      position: { direction: 'right', referencePanel: panel1 },
    });

    const panel3 = event.api.addPanel({
      id: 'tasks',
      component: 'tasks',
      title: 'Tareas',
      position: { direction: 'below', referencePanel: panel2 },
    });

    const panel4 = event.api.addPanel({
      id: 'console',
      component: 'console',
      title: 'Consola',
      position: { direction: 'below', referencePanel: panel1 },
    });

    // Configurar tamaños iniciales
    setTimeout(() => {
      // Redimensionar para una mejor distribución
      const groups = event.api.groups;
      if (groups.length >= 2) {
        try {
          groups[0].api.setSize({ size: 300 } as any); // Explorador de archivos
          groups[1].api.setSize({ size: 300 } as any); // Propiedades
        } catch (e) {
          // Silenciar errores de API si no es compatible
        }
      }
    }, 100);
  };

  const components = {
    tasks: TaskDockWrapper,
    properties: PropertiesDockWrapper,
    console: ConsoleDockWrapper,
    fileExplorer: FileExplorerDockWrapper,
  };

  return (
    <Box style={{ height: '100vh', width: '100%' }}>
      <DockviewReact
        onReady={onReady}
        components={components}
        className="dockview-theme-light"
      />
    </Box>
  );
}