import { useEffect, useCallback } from 'react';
import { ZoneType } from '../../stores/useDockStore';

interface LayoutState {
  navbarHeight: number;
  sidebarWidth: number;
  asidebarWidth: number;
  bottomHeight: number;
  sidebarVisible: boolean;
  asidebarVisible: boolean;
  bottomVisible: boolean;
}

interface PanelLayout {
  id: string;
  component: string;
  title: string;
  zone: ZoneType;
  active: boolean;
}

interface PersistedLayout {
  layout: LayoutState;
  panels: PanelLayout[];
  version: string;
}

const STORAGE_KEY = 'vscode-layout-state';
const CURRENT_VERSION = '1.0.0';

export function useLayoutPersistence() {
  const saveLayout = useCallback((layout: LayoutState, panels: PanelLayout[]) => {
    const persistedLayout: PersistedLayout = {
      layout,
      panels,
      version: CURRENT_VERSION,
    };

    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(persistedLayout));
    } catch (error) {
      console.warn('Failed to save layout to localStorage:', error);
    }
  }, []);

  const loadLayout = useCallback((): PersistedLayout | null => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (!stored) {return null;}

      const parsed: PersistedLayout = JSON.parse(stored);

      // Verificar versión para compatibilidad
      if (parsed.version !== CURRENT_VERSION) {
        console.warn('Layout version mismatch, using default layout');
        return null;
      }

      return parsed;
    } catch (error) {
      console.warn('Failed to load layout from localStorage:', error);
      return null;
    }
  }, []);

  const clearLayout = useCallback(() => {
    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch (error) {
      console.warn('Failed to clear layout from localStorage:', error);
    }
  }, []);

  return {
    saveLayout,
    loadLayout,
    clearLayout,
  };
}

// Hook para auto-guardar layout
export function useAutoSaveLayout(
  layout: LayoutState,
  panels: PanelLayout[],
  debounceMs: number = 1000
) {
  const { saveLayout } = useLayoutPersistence();

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      saveLayout(layout, panels);
    }, debounceMs);

    return () => clearTimeout(timeoutId);
  }, [layout, panels, saveLayout, debounceMs]);
}

// Componente para exportar/importar layout
interface LayoutExportImportProps {
  onImport?: (layout: PersistedLayout) => void;
  getCurrentLayout: () => PersistedLayout;
}

export function LayoutExportImport({ onImport, getCurrentLayout }: LayoutExportImportProps) {
  const exportLayout = () => {
    const layout = getCurrentLayout();
    const dataStr = JSON.stringify(layout, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });

    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `vscode-layout-${new Date().toISOString().split('T')[0]}.json`;
    link.click();

    URL.revokeObjectURL(url);
  };

  const importLayout = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';

    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) {return;}

      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const layout: PersistedLayout = JSON.parse(e.target?.result as string);
          onImport?.(layout);
        } catch (error) {
          console.error('Failed to import layout:', error);
          alert('Error al importar el layout. Verifica que el archivo sea válido.');
        }
      };
      reader.readAsText(file);
    };

    input.click();
  };

  return {
    exportLayout,
    importLayout,
  };
}

// Utilidades para trabajar con layouts
export const LayoutUtils = {
  // Crear un layout por defecto
  createDefaultLayout(): PersistedLayout {
    return {
      layout: {
        navbarHeight: 40,
        sidebarWidth: 250,
        asidebarWidth: 300,
        bottomHeight: 200,
        sidebarVisible: true,
        asidebarVisible: true,
        bottomVisible: true,
      },
      panels: [
        {
          id: 'file-explorer-default',
          component: 'fileExplorer',
          title: 'Explorador',
          zone: 'sidebar',
          active: true,
        },
        {
          id: 'properties-default',
          component: 'properties',
          title: 'Propiedades',
          zone: 'asidebar',
          active: true,
        },
        {
          id: 'console-default',
          component: 'console',
          title: 'Consola',
          zone: 'bottom',
          active: true,
        },
        {
          id: 'tasks-default',
          component: 'tasks',
          title: 'Tareas',
          zone: 'center',
          active: true,
        },
      ],
      version: CURRENT_VERSION,
    };
  },

  // Validar un layout
  validateLayout(layout: any): layout is PersistedLayout {
    return (
      layout &&
      typeof layout === 'object' &&
      layout.version &&
      layout.layout &&
      Array.isArray(layout.panels) &&
      typeof layout.layout.navbarHeight === 'number' &&
      typeof layout.layout.sidebarWidth === 'number' &&
      typeof layout.layout.asidebarWidth === 'number' &&
      typeof layout.layout.bottomHeight === 'number' &&
      typeof layout.layout.sidebarVisible === 'boolean' &&
      typeof layout.layout.asidebarVisible === 'boolean' &&
      typeof layout.layout.bottomVisible === 'boolean'
    );
  },

  // Migrar layout de versiones anteriores
  migrateLayout(oldLayout: any): PersistedLayout {
    // Implementar migraciones aquí si es necesario
    return this.createDefaultLayout();
  },
};