import { useState, useRef, useCallback, useEffect } from 'react';
import { Box } from '@mantine/core';
import './VSCodeLayout.css';

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

interface VSCodeLayoutProps {
  navbar?: React.ReactNode;
  sidebar?: React.ReactNode;
  asidebar?: React.ReactNode;
  bottom?: React.ReactNode;
  children?: React.ReactNode;
  onLayoutChange?: (layout: LayoutState) => void;
  initialLayout?: Partial<LayoutState>;
}

const DEFAULT_LAYOUT: LayoutState = {
  navbarHeight: 40,
  sidebarWidth: 250,
  asidebarWidth: 300,
  bottomHeight: 200,
  sidebarVisible: true,
  asidebarVisible: true,
  bottomVisible: true,
};

export function VSCodeLayout({
  navbar,
  sidebar,
  asidebar,
  bottom,
  children,
  onLayoutChange,
  initialLayout
}: VSCodeLayoutProps) {
  const [layout, setLayout] = useState<LayoutState>(() => ({
    ...DEFAULT_LAYOUT,
    ...initialLayout
  }));
  const [isResizing, setIsResizing] = useState<string | null>(null);
  const layoutRef = useRef<HTMLDivElement>(null);

  // Refs para las posiciones iniciales del mouse
  const initialMousePos = useRef({ x: 0, y: 0 });
  const initialSizes = useRef<Partial<LayoutState>>({});

  // Sincronizar con initialLayout cuando cambie
  useEffect(() => {
    if (initialLayout) {
      setLayout(prev => ({
        ...prev,
        ...initialLayout
      }));
    }
  }, [initialLayout]);

  const updateLayout = useCallback((newLayout: Partial<LayoutState>) => {
    setLayout(prev => {
      const updated = { ...prev, ...newLayout };
      onLayoutChange?.(updated);
      return updated;
    });
  }, [onLayoutChange]);

  const handleMouseDown = useCallback((direction: string, e: React.MouseEvent) => {
    e.preventDefault();
    setIsResizing(direction);
    initialMousePos.current = { x: e.clientX, y: e.clientY };
    initialSizes.current = { ...layout };

    document.body.style.cursor = direction.includes('horizontal') ? 'ew-resize' : 'ns-resize';
    document.body.style.userSelect = 'none';
  }, [layout]);

  const handleMouseMove = useCallback((e: MouseEvent) => {
    if (!isResizing || !layoutRef.current) {return;}

    const deltaX = e.clientX - initialMousePos.current.x;
    const deltaY = e.clientY - initialMousePos.current.y;
    const containerRect = layoutRef.current.getBoundingClientRect();

    switch (isResizing) {
      case 'sidebar-horizontal':
        updateLayout({
          sidebarWidth: Math.max(100, Math.min(600, (initialSizes.current.sidebarWidth || 0) + deltaX))
        });
        break;

      case 'asidebar-horizontal':
        updateLayout({
          asidebarWidth: Math.max(100, Math.min(600, (initialSizes.current.asidebarWidth || 0) - deltaX))
        });
        break;

      case 'bottom-vertical':
        updateLayout({
          bottomHeight: Math.max(100, Math.min(400, (initialSizes.current.bottomHeight || 0) - deltaY))
        });
        break;
    }
  }, [isResizing, updateLayout]);

  const handleMouseUp = useCallback(() => {
    setIsResizing(null);
    document.body.style.cursor = '';
    document.body.style.userSelect = '';
  }, []);

  useEffect(() => {
    if (isResizing) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);

      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
    }
  }, [isResizing, handleMouseMove, handleMouseUp]);

  // Generar grid dinámico que se expande automáticamente
  const generateGridTemplate = () => {
    // Determinar columnas basadas en visibilidad
    const columns = [];
    const navbarCells = [];
    const middleCells = [];
    const bottomCells = [];

    // Columna izquierda (sidebar)
    if (layout.sidebarVisible) {
      columns.push(`${layout.sidebarWidth}px`);
      navbarCells.push('navbar');
      middleCells.push('sidebar');
      bottomCells.push(layout.bottomVisible ? 'sidebar' : 'sidebar');
    }

    // Columna central (siempre presente)
    columns.push('1fr');
    navbarCells.push('navbar');
    middleCells.push('center');
    bottomCells.push(layout.bottomVisible ? 'bottom' : 'center');

    // Columna derecha (asidebar)
    if (layout.asidebarVisible) {
      columns.push(`${layout.asidebarWidth}px`);
      navbarCells.push('navbar');
      middleCells.push('asidebar');
      bottomCells.push(layout.bottomVisible ? 'asidebar' : 'asidebar');
    }

    // Construir template areas - solo incluir filas que tienen contenido
    const rows = [navbarCells.join(' ')];
    rows.push(middleCells.join(' '));

    // Solo agregar la fila bottom si el panel bottom está visible
    if (layout.bottomVisible) {
      rows.push(bottomCells.join(' '));
    }

    const gridTemplateAreas = `"${rows.join('" "')}"`;

    const gridTemplateColumns = columns.join(' ');

    // Construir filas dinámicamente
    const gridRows = [`${layout.navbarHeight}px`, '1fr'];
    if (layout.bottomVisible) {
      gridRows.push(`${layout.bottomHeight}px`);
    }
    const gridTemplateRows = gridRows.join(' ');

    return { gridTemplateAreas, gridTemplateColumns, gridTemplateRows };
  };

  const { gridTemplateAreas, gridTemplateColumns, gridTemplateRows } = generateGridTemplate();

  return (
    <Box
      ref={layoutRef}
      className="vscode-layout"
      style={{
        height: '100vh',
        width: '100vw',
        display: 'grid',
        gridTemplateAreas,
        gridTemplateColumns,
        gridTemplateRows,
        gap: '1px',
        backgroundColor: '#f0f0f0',
        position: 'relative',
      }}
    >
      {/* Navbar */}
      <Box className="layout-zone navbar" style={{ gridArea: 'navbar' }}>
        {navbar}
      </Box>

      {/* Sidebar */}
      {layout.sidebarVisible && (
        <>
          <Box className="layout-zone sidebar" style={{ gridArea: 'sidebar' }}>
            {sidebar}
          </Box>
          <Box
            className="resize-handle resize-handle-vertical"
            style={{
              position: 'absolute',
              top: `${layout.navbarHeight}px`,
              left: `${layout.sidebarWidth - 2}px`,
              width: '4px',
              height: `calc(100vh - ${layout.navbarHeight}px)`,
              cursor: 'ew-resize',
              backgroundColor: 'transparent',
              zIndex: 1000,
            }}
            onMouseDown={(e: React.MouseEvent) => handleMouseDown('sidebar-horizontal', e)}
          />
        </>
      )}

      {/* Center */}
      <Box className="layout-zone center" style={{ gridArea: 'center' }}>
        {children}
      </Box>

      {/* Asidebar */}
      {layout.asidebarVisible && (
        <>
          <Box className="layout-zone asidebar" style={{ gridArea: 'asidebar' }}>
            {asidebar}
          </Box>
          <Box
            className="resize-handle resize-handle-vertical"
            style={{
              position: 'absolute',
              top: `${layout.navbarHeight}px`,
              right: `${layout.asidebarWidth - 2}px`,
              width: '4px',
              height: `calc(100vh - ${layout.navbarHeight}px)`,
              cursor: 'ew-resize',
              backgroundColor: 'transparent',
              zIndex: 1000,
            }}
            onMouseDown={(e: React.MouseEvent) => handleMouseDown('asidebar-horizontal', e)}
          />
        </>
      )}

      {/* Bottom */}
      {layout.bottomVisible && (
        <>
          <Box className="layout-zone bottom" style={{ gridArea: 'bottom' }}>
            {bottom}
          </Box>
          <Box
            className="resize-handle resize-handle-horizontal"
            style={{
              position: 'absolute',
              bottom: `${layout.bottomHeight - 2}px`,
              left: layout.sidebarVisible ? `${layout.sidebarWidth}px` : '0px',
              right: layout.asidebarVisible ? `${layout.asidebarWidth}px` : '0px',
              height: '4px',
              cursor: 'ns-resize',
              backgroundColor: 'transparent',
              zIndex: 1000,
            }}
            onMouseDown={(e: React.MouseEvent) => handleMouseDown('bottom-vertical', e)}
          />
        </>
      )}

      {/* Overlay durante el redimensionamiento */}
      {isResizing && (
        <Box
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            zIndex: 9999,
            cursor: isResizing.includes('horizontal') ? 'ew-resize' : 'ns-resize',
          }}
        />
      )}
    </Box>
  );
}