import { rem, Button } from '@mantine/core';
import {
  Spotlight,
  SpotlightActionData,
  spotlight,
  SpotlightActionGroupData,
} from '@mantine/spotlight';
import {
  IconHome,
  IconDashboard,
  IconFileText,
  IconSearch,
  IconJumpRope,
  IconSteam,
  IconStairs,
} from '@tabler/icons-react';
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { getEchoHeaders } from '@/src/components/utils';
import { useSegment } from '@/src/app/segment.provider';
import { useLocalStorage } from '@mantine/hooks';

export function SpotlightComponent() {
  const [readyState] = useLocalStorage({ key: 'nvReadyState', defaultValue: '' });

  const { track } = useSegment();
  const {
    isLoading: loadingWorkflows,
    data: workflows,
    error,
  } = useQuery<any[]>({
    queryKey: ['workflows'],
    enabled: Object.keys(getEchoHeaders()).length > 0 && !!readyState,
    refetchOnWindowFocus: 'always',
    refetchInterval: 1000,
    queryFn: () =>
      fetch('/api/workflows', {
        headers: {
          ...getEchoHeaders(),
        },
      }).then((res) => res.json()),
  });

  const router = useRouter();
  const workflowsCommands =
    workflows?.map((workflow) => ({
      id: workflow.workflowId,
      label: `Workflow: ${workflow.workflowId}`,
      description: `Step Count: ${workflow.steps?.length}`,
      onClick: () => {
        track('Spotlight Item Clicked', {
          item: 'Workflow Page',
        });
        router.push(`/workflow/${workflow.workflowId}`);
      },
      leftSection: <IconJumpRope style={{ width: rem(24), height: rem(24) }} stroke={1.5} />,
    })) || [];
  const actions: (SpotlightActionGroupData | SpotlightActionData)[] = [
    {
      id: 'home',
      label: 'Home',
      description: 'Get to home page',
      onClick: () => {
        track('Spotlight Item Clicked', {
          item: 'Home',
        });
        router.push('/');
      },
      leftSection: <IconHome style={{ width: rem(24), height: rem(24) }} stroke={1.5} />,
    },

    {
      id: 'documentation',
      label: 'Documentation',
      description: 'Visit documentation to lean more about all features',
      onClick: () => {
        track('Spotlight Item Clicked', {
          item: 'Documentation',
        });

        window.open(
          'https://novuhq.notion.site/Novu-Echo-Documentation-02e5d95d7a5e467fa8a97792bdb5f2db',
          '_blank'
        );
      },
      leftSection: <IconFileText style={{ width: rem(24), height: rem(24) }} stroke={1.5} />,
    },
    {
      group: 'Workflows',
      actions: [...workflowsCommands],
    },
    {
      group: 'Steps',
      actions: [
        ...(workflows
          ?.map((workflow) =>
            workflow?.steps?.map((step: any) => ({
              id: step.stepId,
              label: `Step: ${workflow.workflowId} -> ${step.stepId}`,
              description: `Workflow: ${workflow.workflowId}`,
              onClick: () => {
                track('Spotlight Item Clicked', {
                  item: 'Workflow Step',
                });

                router.push(`/workflow/${workflow.workflowId}/steps/${step.stepId}`);
              },
              leftSection: <IconStairs style={{ width: rem(24), height: rem(24) }} stroke={1.5} />,
            }))
          )
          .flat() || []),
      ],
    },
  ];

  return (
    <Spotlight
      onSpotlightOpen={() => {
        track('Spotlight Opened');
      }}
      shortcut="mod + k"
      actions={actions}
      nothingFound="Nothing found..."
      highlightQuery
      searchProps={{
        leftSection: <IconSearch style={{ width: rem(20), height: rem(20) }} stroke={1.5} />,
        placeholder: 'Search...',
      }}
    />
  );
}
