import { useCallback, useMemo } from 'react';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { WorkspaceView } from 'officerdev';
import { useIsMobile } from 'hooks/useIsMobile';
import { usePanelChannel } from 'hooks/usePanelChannel';
import { useDashboardState } from 'state/useDashboardState';
import type { TaskSummary } from 'officerdev';

import { AutomationList } from './AutomationList';
import { AutomationDetail } from './AutomationDetail';

export type { TaskSummary as SelectedTask };

const defaultLayout: LayoutNode = {
  type: 'group',
  id: 'automation-root',
  direction: 'horizontal',
  children: [
    { node: { type: 'panel', id: 'automation-list', appType: null }, size: 30 },
    { node: { type: 'panel', id: 'automation-detail', appType: null }, size: 70 },
  ],
};

export const Automation = () => {
  const workspace = useDashboardState<LayoutNode>('screens/automation', defaultLayout);
  const [selected] = usePanelChannel<TaskSummary | null>('automation:selected-task', null);
  const isMobile = useIsMobile();

  const panelComponents: PanelComponents = useMemo(
    () => ({
      'automation-list': AutomationList,
      'automation-detail': AutomationDetail,
    }),
    [],
  );

  const mobilePanelId = isMobile && selected ? 'automation-detail' : undefined;
  const onMobileBack = useCallback(() => {}, []);

  if (!workspace.isLoaded) return null;

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView
        workspace={workspace}
        locked
        components={panelComponents}
        mobilePanelId={mobilePanelId}
        onMobilePanelChange={mobilePanelId ? () => onMobileBack() : undefined}
      />
    </div>
  );
};
