import playgroundApp from '@playground-data';
import {
  component$,
  isBrowser,
  useSignal,
  useStore,
  useStyles$,
  useTask$,
  useVisibleTask$,
} from '@qwik.dev/core';
import type { DocumentHead, RequestHandler } from '@qwik.dev/router';
import type { ReplAppInput } from '~/repl/types';
import { setReplCorsHeaders } from '~/utils/utils';
import { Header } from '../../components/header/header';
import { PanelToggle } from '../../components/panel-toggle/panel-toggle';
import { Repl } from '../../repl/ui';
import { createPlaygroundShareUrl, parsePlaygroundShareUrl } from '../../repl/ui/repl-share-url';
import styles from './playground.css?inline';

export default component$(() => {
  useStyles$(styles);
  const shareUrlTmr = useSignal<ReturnType<typeof setTimeout> | undefined>(undefined);

  const store = useStore<ReplAppInput>(() => ({
    files: playgroundApp.inputs,
    version: '',
    buildMode: 'development',
    entryStrategy: 'segment',
    outOfOrderStreaming: true,
  }));

  const panelStore = useStore(() => ({
    active: 'Input',
    list: ['Input', 'Output', 'Console'],
  }));

  useVisibleTask$(() => {
    // run once on the client
    const shareData = parsePlaygroundShareUrl(location.hash.slice(1));
    if (shareData) {
      store.version = shareData.version;
      store.buildMode = shareData.buildMode;
      store.entryStrategy = shareData.entryStrategy;
      store.outOfOrderStreaming = shareData.outOfOrderStreaming;
      store.files = shareData.files;
    }
  });

  useTask$(({ track }) => {
    track(() => store.buildMode);
    track(() => store.entryStrategy);
    track(() => store.outOfOrderStreaming);
    track(() => store.version);
    track(() => store.files.forEach((f) => f.code));

    if (isBrowser) {
      if (store.version) {
        clearTimeout(shareUrlTmr.value);

        shareUrlTmr.value = setTimeout(() => {
          const shareUrl = createPlaygroundShareUrl(store);
          history.replaceState({}, '', shareUrl);
        }, 1000);
      }
    }
  });

  return (
    <div
      class={{
        playground: true,
        'full-width': true,
        'fixed-header': true,
        'repl-theme-docs': true,
      }}
    >
      <Header />
      <PanelToggle panelStore={panelStore} />
      <main class="playground-main">
        <div
          class={{
            repl: true,
            'repl-mobile-paged': true,
            'repl-mobile-paged-3': true,
            'repl-mobile-panel-output': panelStore.active === 'Output',
            'repl-mobile-panel-console': panelStore.active === 'Console',
          }}
        >
          <Repl
            input={store}
            enableCopyToPlayground={false}
            enableDownload={true}
            enableInputDelete={true}
            enableMainSplitter={true}
            editorTheme="github-light"
          />
        </div>
      </main>
    </div>
  );
});

export const head: DocumentHead = {
  title: 'Playground',
};

export const onGet: RequestHandler = ({ cacheControl, headers }) => {
  cacheControl({
    public: true,
    maxAge: 3600,
  });

  setReplCorsHeaders(headers);
};
