'use client';

import Link from 'next/link';
import Image from 'next/image';
import {
  Alert,
  Badge,
  Button,
  Container,
  Input,
  Modal,
  Tooltip,
  Text,
  Code,
  Kbd,
} from '@mantine/core';
import { IconInfoCircle, IconRefresh, IconSearch } from '@tabler/icons-react';
import React, { useEffect, useMemo, useState } from 'react';
import { notifications } from '@mantine/notifications';
import { useQuery } from '@tanstack/react-query';
import { useDisclosure, useLocalStorage } from '@mantine/hooks';
import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer-continued';
import { modals } from '@mantine/modals';
import { spotlight } from '@mantine/spotlight';
import { getEchoHeaders } from '@/src/components/utils';
import { SpotlightComponent } from '@/src/components/Spotlight/Spotlight';
import { SyncModal } from '@/src/components/TopNavBar/SyncModal';

export function TopNavBar({ echoUrl }: { echoUrl: string }) {
  const [readyState, setReadyState] = useLocalStorage({ key: 'nvReadyState', defaultValue: '' });
  const { isLoading: loadingHealth, data: echoHealth } = useQuery<{ success: true }>({
    queryKey: ['health', echoUrl],
    refetchOnWindowFocus: 'always',
    refetchInterval: 2000,
    enabled: !!echoUrl,
    queryFn: () =>
      fetch('/api/echo/health', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getEchoHeaders(),
        },
        body: JSON.stringify({ url: echoUrl }),
      }).then((res) => res.json()),
  });

  useEffect(() => {
    if (echoHealth?.success) {
      setReadyState('true');
    }
  }, [echoHealth]);

  return (
    <div
      style={{
        height: '100%',
        padding: '0 20px',
        width: '100%',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
      }}
    >
      <SpotlightComponent />

      <div style={{}}>
        <Link href="/" style={{ textDecoration: 'none', color: 'initial' }}>
          <Image
            src="/logo/novu-logo-white-dark-background.svg"
            alt="Logo"
            width={110}
            height={40}
          />
          <span style={{ fontSize: 11, position: 'relative', left: -56 }}>dev studio.</span>
        </Link>
      </div>
      <Input
        onClick={(e) => {
          e.preventDefault();
          spotlight.open();
        }}
        onKeyDown={(e) => {
          e.preventDefault();
        }}
        onFocus={(e) => {
          e.preventDefault();
        }}
        placeholder="Search"
        leftSection={<IconSearch size={14} />}
        rightSection={
          <div style={{ minWidth: 70, display: 'flex' }}>
            <Kbd size="xs">⌘ + K</Kbd>
          </div>
        }
      />

      {echoUrl ? (
        <div>
          {echoHealth?.success || loadingHealth ? (
            <Tooltip label={`Echo successfully running at: ${echoUrl}`}>
              <Badge color="#a4a4a4" variant="outline" style={{ marginRight: 15, fontSize: 9 }}>
                <Badge
                  color="green"
                  variant="dot"
                  style={{
                    backgroundColor: 'transparent',
                    padding: 0,
                    border: 0,
                    position: 'relative',
                  }}
                />
                Connected
              </Badge>
            </Tooltip>
          ) : (
            <Tooltip label={`Could not connect at: ${echoUrl}`}>
              <Badge color="#a4a4a4" variant="outline" style={{ marginRight: 15, fontSize: 9 }}>
                <Badge
                  color="red"
                  variant="dot"
                  style={{
                    backgroundColor: 'transparent',
                    padding: 0,
                    border: 0,
                    position: 'relative',
                  }}
                />
                Disconnected
              </Badge>
            </Tooltip>
          )}
          <SyncModal connected={echoHealth?.success || loadingHealth} />
        </div>
      ) : null}
    </div>
  );
}
