import { useRef, useState } from 'react';
import { useSidePanelLayout } from '../../hooks/useSidePanelLayout';
import { VerticalResizeHandle } from '../layout/VerticalResizeHandle';
import { SideInfoPanel } from './SideInfoPanel';

interface Props {
  /** TaskListPanel または RailPanel を含む上半分。 */
  upper: React.ReactNode;
  activeWidgetSlug?: string;
  onActiveWidgetSlugChange?: (slug: string) => void;
  /** rail/mobile 等の狭い viewport で default を collapsed にしたい場合に指定。 */
  defaultCollapsed?: boolean;
}

let _idSeq = 0;

export function TaskListWithSidePanel({
  upper,
  activeWidgetSlug,
  onActiveWidgetSlugChange,
  defaultCollapsed,
}: Props) {
  const { listHeightPct, setListHeightPct, collapsed, toggleCollapsed, resetHeight } = useSidePanelLayout();
  const initOverrideRef = useRef<boolean>(false);
  if (defaultCollapsed && !initOverrideRef.current && localStorage.getItem('dashboard.collapsed') === null) {
    initOverrideRef.current = true;
    toggleCollapsed();
  }
  const [parentId] = useState(() => `tlspl-${++_idSeq}`);

  const upperFlex = collapsed ? '1 1 auto' : `0 0 ${listHeightPct}%`;
  const lowerFlex = collapsed ? '0 0 auto' : `0 0 ${100 - listHeightPct}%`;

  return (
    <div
      data-side-panel-parent={parentId}
      className="flex flex-col h-full min-h-0 overflow-hidden"
    >
      <div style={{ flex: upperFlex, minHeight: 0 }} className="overflow-hidden">
        {upper}
      </div>
      {!collapsed && (
        <VerticalResizeHandle
          parentSelector={`[data-side-panel-parent="${parentId}"]`}
          onResize={setListHeightPct}
          onResizeEnd={setListHeightPct}
          onReset={resetHeight}
        />
      )}
      <div style={{ flex: lowerFlex, minHeight: collapsed ? 'auto' : 0 }} className="overflow-hidden border-t border-hairline">
        <SideInfoPanel
          activeSlug={activeWidgetSlug}
          onActiveSlugChange={onActiveWidgetSlugChange}
          collapsed={collapsed}
          onToggleCollapse={toggleCollapsed}
        />
      </div>
    </div>
  );
}
