import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useSearchParams } from 'react-router';
import type { EphemeralPanels } from '../../components/Workspace';
import { FileViewerHeader, FileViewerBody } from '../../apps/FileViewer';
import {
  singleViewerLayout,
  viewerWithEphemeralLayout,
  viewerWithEphemeralSplitLayout,
  singleChatLayout,
} from './layouts';
import { ViewerProvider, EphemeralProvider, Ephemeral2Provider, ChatEphemeralBody } from './Providers';

const EPHEMERAL_KEYS = [
  'view',
  'ephemeral',
  'ephemeralRoot',
  'ephemeral2',
  'ephemeral2Root',
  'ephemeral2Auto',
  'chatContext',
  'chatType',
];

export const useFileViewerPanels = (): EphemeralPanels | null => {
  const [searchParams, setSearchParams] = useSearchParams();
  const didClean = useRef(false);

  // Clear stale ephemeral params on mount (page refresh)
  useEffect(() => {
    if (didClean.current) return;
    didClean.current = true;
    if (EPHEMERAL_KEYS.some((k) => searchParams.has(k))) {
      setSearchParams((prev) => {
        const next = new URLSearchParams(prev);
        EPHEMERAL_KEYS.forEach((k) => next.delete(k));
        return next;
      });
    }
  }, []);

  const viewPath = searchParams.get('view');
  const ephemeralPath = searchParams.get('ephemeral');
  const ephemeral2Path = searchParams.get('ephemeral2');
  const chatContext = searchParams.get('chatContext');

  const layout = chatContext
    ? singleChatLayout
    : viewPath && ephemeralPath && ephemeral2Path
      ? viewerWithEphemeralSplitLayout
      : viewPath && ephemeralPath
        ? viewerWithEphemeralLayout
        : singleViewerLayout;

  const onCloseViewer = useCallback(() => setSearchParams({}), [setSearchParams]);

  const onCloseEphemeral = useCallback(
    () =>
      setSearchParams((prev) => {
        const next = new URLSearchParams(prev);
        next.delete('ephemeral');
        next.delete('ephemeralRoot');
        next.delete('ephemeral2');
        next.delete('ephemeral2Root');
        next.delete('ephemeral2Auto');
        return next;
      }),
    [setSearchParams],
  );

  const onCloseEphemeral2 = useCallback(
    () =>
      setSearchParams((prev) => {
        const next = new URLSearchParams(prev);
        next.delete('ephemeral2');
        next.delete('ephemeral2Root');
        next.delete('ephemeral2Auto');
        return next;
      }),
    [setSearchParams],
  );

  const onCloseChat = useCallback(
    () =>
      setSearchParams((prev) => {
        const next = new URLSearchParams(prev);
        next.delete('chatContext');
        next.delete('chatType');
        return next;
      }),
    [setSearchParams],
  );

  const components = useMemo(
    () => ({
      'files-viewer': {
        provider: ViewerProvider,
        header: FileViewerHeader,
        component: FileViewerBody,
        onClose: onCloseViewer,
      },
      'files-ephemeral': {
        provider: EphemeralProvider,
        header: FileViewerHeader,
        component: FileViewerBody,
        onClose: onCloseEphemeral,
      },
      'files-ephemeral2': {
        provider: Ephemeral2Provider,
        header: FileViewerHeader,
        component: FileViewerBody,
        onClose: onCloseEphemeral2,
      },
      'files-chat': {
        component: ChatEphemeralBody,
        onClose: onCloseChat,
      },
    }),
    [onCloseViewer, onCloseEphemeral, onCloseEphemeral2, onCloseChat],
  );

  if (!viewPath && !chatContext) return null;
  const onClose = onCloseViewer;
  return { layout, components, defaultBaseSize: 40, onClose };
};

export type UseFileViewerPanelsType = ReturnType<typeof useFileViewerPanels>;
