'use client';

import { Divider, Kbd, NavLink, Skeleton, Text, Tooltip } from '@mantine/core';
import Link from 'next/link';
import { IconJumpRope } from '@tabler/icons-react';
import React, { useEffect } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { usePathname, useRouter } from 'next/navigation';
import { getEchoHeaders } from '@/src/components/utils';
import { NodeIcon } from '@/src/components/Node/NodeIcon';
import classes from './NavBar.module.css';
import { useSegment } from '@/src/app/segment.provider';

export function NavBar({ workflows, isLoading }: any) {
  const pathname = usePathname();
  const { track } = useSegment();
  const router = useRouter();
  const queryClient = useQueryClient();

  const prefetch = (workflowId: string, stepId: string) => {
    queryClient.prefetchQuery({
      queryKey: ['preview', workflowId, stepId, {}],
      queryFn: () =>
        fetch(`/api/workflows/${workflowId}/preview/${stepId}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...getEchoHeaders(),
          },
          body: JSON.stringify({
            inputs: {},
          }),
        })
          .then((res) => res.json())
          .then((res) => res.outputs),
      // Prefetch only fires when data is older than the staleTime,
      // so in a case like this you definitely want to set one
      staleTime: 60000,
    });
  };

  const groceries = [
    {
      emoji: '🍎',
      value: 'Apples',
      description:
        'Crisp and refreshing fruit. Apples are known for their versatility and nutritional benefits. They come in a variety of flavors and are great for snacking, baking, or adding to salads.',
    },
    {
      emoji: '🍌',
      value: 'Bananas',
      description:
        'Naturally sweet and potassium-rich fruit. Bananas are a popular choice for their energy-boosting properties and can be enjoyed as a quick snack, added to smoothies, or used in baking.',
    },
    {
      emoji: '🥦',
      value: 'Broccoli',
      description:
        'Nutrient-packed green vegetable. Broccoli is packed with vitamins, minerals, and fiber. It has a distinct flavor and can be enjoyed steamed, roasted, or added to stir-fries.',
    },
  ];

  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'space-between',
        justifyContent: 'space-between',
        flexDirection: 'column',
        height: '100%',
      }}
    >
      <div>
        {isLoading && (
          <>
            <Skeleton visible style={{ marginBottom: 10 }}>
              <div style={{ height: '40px' }} />
            </Skeleton>
            <Skeleton visible style={{ marginBottom: 10 }}>
              <div style={{ height: '40px' }} />
            </Skeleton>
            <Skeleton visible style={{ marginBottom: 10 }}>
              <div style={{ height: '40px' }} />
            </Skeleton>
          </>
        )}

        {!isLoading && !workflows?.length ? (
          <div style={{ textAlign: 'center', fontSize: 14, marginTop: 15 }}>No workflows found</div>
        ) : null}

        {workflows?.map((workflow) => (
          <NavLink
            variant="subtle"
            active={pathname?.includes(`/workflow/${workflow.workflowId}`)}
            onClick={() => router.push(`/workflow/${workflow.workflowId}`)}
            key={workflow.workflowId}
            prefetch
            component={Link}
            href={`/workflow/${workflow.workflowId}`}
            label={workflow.workflowId}
            leftSection={<IconJumpRope size="1rem" stroke={1.5} />}
            childrenOffset={28}
          >
            {workflow.steps.map((step) => (
              <NavLink
                variant="subtle"
                active={pathname === `/workflow/${workflow.workflowId}/steps/${step.stepId}`}
                key={step.stepId}
                onMouseEnter={() => prefetch(workflow.workflowId, step.stepId)}
                component={Link}
                prefetch
                leftSection={
                  <span
                    style={{ position: 'relative', top: 5, fontSize: 10 }}
                    className={classes.icon}
                  >
                    <NodeIcon channel={step.type} />
                  </span>
                }
                href={`/workflow/${workflow.workflowId}/steps/${step.stepId}`}
                label={step.stepId}
              />
            ))}
          </NavLink>
        ))}
      </div>

      <div style={{ textAlign: 'center' }}>
        <Divider my="sm" />
        <Text size="xs">
          <a
            onClick={() => track('Documentation Link Clicked')}
            href="https://docs.novu.co/echo/introduction"
            target="_blank"
            rel="noreferrer"
            style={{ textDecoration: 'none', color: 'inherit', fontWeight: 'bold' }}
          >
            View Documentation
          </a>
        </Text>
      </div>
    </div>
  );
}
