import { Input, Loader, Tooltip } from '@mantine/core';
import { IconCheck, IconExclamationCircle, IconHexagonLetterX } from '@tabler/icons-react';
import { useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useLocalStorage, useWindowEvent } from '@mantine/hooks';
import { getEchoHeaders } from '@/src/components/utils';

const DEFAULT_ECHO_URL = 'http://localhost:4000/api/echo';

export function EdgeUrlInput({
  onEdgeValidity,
  onUrlChange,
  defaultUrl = DEFAULT_ECHO_URL,
}: {
  onEdgeValidity: (isValid: boolean) => void;
  onUrlChange: (url: string) => void;
  defaultUrl?: string;
}) {
  const [echoUrlLocal] = useLocalStorage({ key: 'echo_url', defaultValue: '' });
  const [url, setUrl] = useState('');

  const [firstLoad, setFirstLoad] = useState(true);
  const mutation = useMutation<{ success: boolean }, unknown, string>({
    mutationFn: (urlData) =>
      fetch('/api/echo/health', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getEchoHeaders(),
        },
        body: JSON.stringify({ url: urlData }),
      }).then((res) => res.json()),
  });

  useWindowEvent('focus', () => {
    if (firstLoad) return;

    checkEchoUrl();
  });

  useEffect(() => {
    setFirstLoad(false);
  }, []);

  async function checkEchoUrl() {
    if (!url) return;

    const response = await mutation.mutateAsync(url);

    if (response?.success) {
      onEdgeValidity(true);
      onUrlChange(url);
    } else {
      onEdgeValidity(false);
    }
  }

  useEffect(() => {
    const delayDebounceFn = setTimeout(checkEchoUrl, 500);
    return () => clearTimeout(delayDebounceFn);
  }, [url]);

  useEffect(() => {
    if (echoUrlLocal) {
      setUrl(echoUrlLocal);
    } else if (defaultUrl) {
      setUrl(defaultUrl);
    }
  }, [echoUrlLocal, defaultUrl]);

  async function testUrl(data: string) {
    setUrl(data);
  }

  function CheckStatusIcon() {
    return (
      <>
        {mutation.isPending ? <Loader size={16} /> : null}
        {mutation.data?.success ? <IconCheck color="green" /> : null}
        {!mutation.isPending && !mutation.data?.success ? (
          <IconExclamationCircle color="#f45c5c" />
        ) : null}
      </>
    );
  }

  return (
    <Input.Wrapper
      data-testid="echo-endpoint-wrapper"
      style={{ marginTop: 20 }}
      label="Echo Endpoint"
      withAsterisk
      description="Provide the full URL of your local Echo Endpoint"
      error={
        !mutation.isPending && !mutation.data?.success
          ? 'Could not locate a valid Echo endpoint'
          : null
      }
    >
      <Input
        data-testid="edge-endpoint-url"
        onChange={(e) => testUrl(e.target.value)}
        rightSection={<CheckStatusIcon />}
        placeholder="Your local Echo Endpoint"
        defaultValue={url}
      />
    </Input.Wrapper>
  );
}
