import { useCallback } from 'react';
import { Panel } from './Panel';
import { useSplitResize } from '../layout/useLayoutTree';

export function SplitNode({
  node,
  path,
  onResize,
  dragState,
  onEdgeDown,
  onDropZoneHover,
}) {
  const handleResize = useCallback(
    (ratio) => onResize(path, ratio),
    [path, onResize]
  );
  const startResize = useSplitResize(node.direction, handleResize);

  const r = node.ratio;
  const isHorizontal = node.direction === 'horizontal';
  const splitStyle = isHorizontal
    ? {
        gridTemplateColumns: `minmax(0, ${r}fr) var(--gutter-size) minmax(0, ${1 - r}fr)`,
        gridTemplateRows: 'minmax(0, 1fr)',
      }
    : {
        gridTemplateColumns: 'minmax(0, 1fr)',
        gridTemplateRows: `minmax(0, ${r}fr) var(--gutter-size) minmax(0, ${1 - r}fr)`,
      };

  return (
    <div className={`split split--${node.direction}`} style={splitStyle}>
      <div className="split-pane split-pane--first">
        <LayoutNode
          node={node.first}
          path={[...path, 'first']}
          onResize={onResize}
          dragState={dragState}
          onEdgeDown={onEdgeDown}
          onDropZoneHover={onDropZoneHover}
        />
      </div>
      <div className="split-gutter" onMouseDown={startResize} />
      <div className="split-pane split-pane--second">
        <LayoutNode
          node={node.second}
          path={[...path, 'second']}
          onResize={onResize}
          dragState={dragState}
          onEdgeDown={onEdgeDown}
          onDropZoneHover={onDropZoneHover}
        />
      </div>
    </div>
  );
}

function LayoutNode({ node, path, onResize, dragState, onEdgeDown, onDropZoneHover }) {
  if (node.type === 'leaf') {
    const isDragging = dragState?.panelId === node.panelId;
    const isDropTarget = dragState && dragState.panelId !== node.panelId;
    const activeDropEdge =
      isDropTarget && dragState.activeZone?.targetId === node.panelId
        ? dragState.activeZone.edge
        : null;

    return (
      <Panel
        panelId={node.panelId}
        isDragging={isDragging}
        isDropTarget={isDropTarget}
        activeDropEdge={activeDropEdge}
        onEdgeDown={onEdgeDown}
        onDropZoneHover={onDropZoneHover}
      />
    );
  }

  return (
    <SplitNode
      node={node}
      path={path}
      onResize={onResize}
      dragState={dragState}
      onEdgeDown={onEdgeDown}
      onDropZoneHover={onDropZoneHover}
    />
  );
}

export function LayoutRoot({ layout, dragState, onResize, onEdgeDown, onDropZoneHover }) {
  if (!layout) return null;

  return (
    <LayoutNode
      node={layout}
      path={[]}
      onResize={onResize}
      dragState={dragState}
      onEdgeDown={onEdgeDown}
      onDropZoneHover={onDropZoneHover}
    />
  );
}
