import { useEffect, useRef, useState, useMemo } from 'react';
import {
  DockviewReact,
  DockviewReadyEvent,
  DockviewApi,
  themeLight,
  themeDark,
} from 'dockview';
import { useMantineColorScheme, useComputedColorScheme } from '@mantine/core';
import { useDockviewStore } from '../stores/useDockviewStore';
import { Welcome } from './Welcome/Welcome';
import { ColorSchemeToggle } from './ColorSchemeToggle/ColorSchemeToggle';
import 'dockview/dist/styles/dockview.css';

export function DockviewLayoutManager() {
  const hostRef = useRef<HTMLDivElement | null>(null);
  const apiRef = useRef<DockviewApi | null>(null);
  const { layoutConfig, setLayoutConfig } = useDockviewStore();

  // 🎨 Detecta automáticamente el tema de Mantine (light / dark / system)
  const { colorScheme } = useMantineColorScheme();
  const computedScheme = useComputedColorScheme('light', {
    getInitialValueInEffect: true,
  });

  // 🧱 Layout por defecto
  const createDefaultLayout = (api: DockviewApi) => {
    // ✅ El primer panel no debe tener "position"
    api.addPanel({
      id: 'welcome',
      component: 'welcome',
      title: 'Bienvenido',
    });

    // ✅ Los siguientes sí pueden usar dirección
    api.addPanel({
      id: 'toggle',
      component: 'toggle',
      title: 'Cambiar tema',
      position: { direction: 'right' },
    });
  };

  // ⚡ Inicializa Dockview al estar listo
  const onReady = (event: DockviewReadyEvent) => {
    const api = event.api;
    apiRef.current = api;

    if (layoutConfig) {
      try {
        api.fromJSON(layoutConfig);
      } catch {
        console.warn('Error loading saved Dockview layout, using default');
        createDefaultLayout(api);
      }
    } else {
      createDefaultLayout(api);
    }

    // 🧠 Guarda el layout cuando cambia
    api.onDidLayoutChange(() => {
      const saved = api.toJSON();
      setLayoutConfig(saved);
    });
  };

  // 🌗 Determina el tema actual y aplica estilos personalizados
  const isDark = computedScheme === 'dark';
  const dockviewTheme = isDark ? themeDark : themeLight;

  // 🎨 Personalización Dockview mediante variables CSS
  const dockviewCustomTheme = useMemo(() => {
    const baseTheme = isDark ? themeDark : themeLight;
    return {
      ...baseTheme,
    };
  }, [isDark]);

  return (
    <div
      ref={hostRef}
      style={{
        flex: 1,
        width: '100%',
        height: '100%',
        display: 'flex',
        overflow: 'hidden',
        transition: 'background-color 0.3s ease-in-out',
        backgroundColor: isDark ? '#1A1B1E' : '#f5f6f7',
      }}
    >
      <DockviewReact
        theme={dockviewCustomTheme}
        components={{
          welcome: (props) => (
            <ResponsivePanel component="welcome" {...props} />
          ),
          toggle: (props) => (
            <ResponsivePanel component="toggle" {...props} />
          ),
        }}
        onReady={onReady}
      />
    </div>
  );
}

// ✅ Panel adaptable al tamaño
function ResponsivePanel({
  component,
  api,
}: {
  component: 'welcome' | 'toggle';
  api: any;
}) {
  const [size, setSize] = useState({ width: api.width, height: api.height });

  useEffect(() => {
    const unsubscribe = api.onDidDimensionsChange(() => {
      setSize({ width: api.width, height: api.height });
    });
    return () => unsubscribe.dispose();
  }, [api]);

  if (component === 'welcome') {
    return <Welcome width={size.width} height={size.height} />;
  }

  if (component === 'toggle') {
    return <ColorSchemeToggle />;
  }

  return null;
}
