'use client';

import React, { useEffect, useState } from 'react';
import { AppShell, AppShellHeader, AppShellNavbar, AppShellMain, Burger } from '@mantine/core';
import { Notifications } from '@mantine/notifications';
import { useLocalStorage } from '@mantine/hooks';
import { useQuery } from '@tanstack/react-query';
import Head from 'next/head';
import { NavBar } from '@/src/components/NavBar/NavBar';
import { TopNavBar } from '@/src/components/TopNavBar/TopNavBar';
import { SpotlightComponent } from '@/src/components/Spotlight/Spotlight';
import { getEchoHeaders } from '@/src/components/utils';

export const Favicon = () => {
  const [iconUrl, setIconUrl] = useState<string>('/icon-light.png');
  <Head>
    <link rel="icon" href={iconUrl} />
  </Head>;
};

export function useWorkflows() {
  const [echoUrl] = useLocalStorage({
    key: 'echo_url',
    defaultValue: '',
  });

  return useQuery<any[]>({
    queryKey: ['workflows'],
    enabled: !!echoUrl,
    refetchOnWindowFocus: 'always',
    refetchInterval: 1500,
    queryFn: () =>
      fetch('/api/workflows', {
        headers: {
          ...getEchoHeaders(),
        },
      }).then((res) => res.json()),
  });
}

export function useColorSchemeFavicon() {
  useEffect(() => {
    const updateFavicon = (colorScheme) => {
      const faviconFolder = '/favicon';
      const iconHref = colorScheme === 'dark' ? '/logo-dark' : '/logo';
      document.querySelectorAll('link[rel="icon"]').forEach((link) => {
        if (link instanceof HTMLLinkElement) {
          if (link.href.includes('.png')) {
            link.href = `${faviconFolder}${iconHref}.png`;
          } else if (link.href.includes('.svg')) {
            link.href = `${faviconFolder}${iconHref}.svg`;
          } else {
            // No-op - unsupported favicon type
          }
        }
      });
    };

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const listener = (e) => {
      updateFavicon(e.matches ? 'dark' : '');
    };

    // Initial update
    updateFavicon(mediaQuery.matches ? 'dark' : '');

    mediaQuery.addEventListener('change', listener);

    return () => {
      mediaQuery.removeEventListener('change', listener);
    };
  }, []);
}

export function BodyContent({ children }: { children: React.ReactNode }) {
  const [echoUrl] = useLocalStorage({
    key: 'echo_url',
    defaultValue: '',
  });
  const { isLoading, data: workflows } = useWorkflows();

  useColorSchemeFavicon();

  return (
    <>
      <Notifications />
      <SpotlightComponent />

      <AppShell
        header={{ height: 60 }}
        navbar={
          echoUrl && workflows?.length
            ? {
                width: 300,
                breakpoint: 'sm',
                collapsed: { mobile: false },
              }
            : {
                width: 0,
                breakpoint: 'sm',
              }
        }
        padding="md"
      >
        <AppShellHeader>
          <Burger hiddenFrom="sm" size="sm" />
          <TopNavBar echoUrl={echoUrl} />
        </AppShellHeader>

        {echoUrl && workflows?.length ? (
          <AppShellNavbar p="md">
            <NavBar workflows={workflows} isLoading={isLoading} />
          </AppShellNavbar>
        ) : null}

        <AppShellMain>{children}</AppShellMain>
      </AppShell>
    </>
  );
}
