import {
  Alert,
  Fieldset,
  JsonInput,
  Stack,
  Text,
  TextInput,
} from '@mantine/core';
import { IconHandLittleFinger } from '@tabler/icons-react';
import { __ } from '@wordpress/i18n';
import { useState } from 'react';
import useSWR from 'swr';
import { useOptionsContext } from '../components/Options';
import { post } from '../utils/post';

export default function GeoSettings() {
  const { getOptions, updateOptions } = useOptionsContext();

  const ipstack_api_key = getOptions('geolocalization.ipstack.api_key');

  const [apiKey, setApiKey] = useState(ipstack_api_key);

  const { data, error, isLoading, isValidating, mutate } = useSWR(
    'wp_bannerize_get_geo',
    post,
  );

  const handleChange = event => {
    const apiKey = event.currentTarget.value;

    updateOptions('geolocalization.ipstack.api_key', apiKey);

    setApiKey(event.currentTarget.value);

    setTimeout(mutate, 1000);
  };

  const isGeoError = data && data.error;

  return (
    <Stack py={16}>
      {!apiKey && (
        <Alert color="yellow" title="Warning!" icon={<IconHandLittleFinger />}>
          {__(
            'To start, or continue using the Geolocalizer features, you must register with one of the services listed below.',
            'wp-bannerize',
          )}
        </Alert>
      )}

      <Fieldset legend={__('IPStack', 'wp-bannerize')}>
        <Stack>
          {isGeoError ? (
            <Alert
              color="red"
              title={`Error: ${data.error.type} - ${data.error.code}`}>
              <Text size="xs">{data.error.info}</Text>
            </Alert>
          ) : null}
          {apiKey && !isGeoError ? (
            <Alert color="teal" title={__('Success!', 'wp-bannerize')}>
              <Text size="xs">
                {__('Great! You have an API KEY on', 'wp-bannerize')}{' '}
                <a target="_blank" href="https://ipstack.com/">
                  IPStack
                </a>{' '}
                service.
              </Text>
            </Alert>
          ) : (
            <Alert title="Get your API KEY">
              <Text size="xs">
                {__('Sign up for Free on', 'wp-bannerize')}{' '}
                <a target="_blank" href="https://ipstack.com/">
                  IPStack
                </a>{' '}
                {__('service to get your', 'wp-bannerize')}{' '}
                <strong> API KEY</strong>
              </Text>
            </Alert>
          )}
          <TextInput
            size="xs"
            label="API KEY"
            value={apiKey}
            description={__(
              'Enter your API KEY to enable the Geolocalizer features',
              'wp-bannerize',
            )}
            placeholder="0e0bf1..."
            onChange={handleChange}
          />
          {data && !isGeoError && (
            <JsonInput
              size="xs"
              variant="filled"
              readOnly
              label={__('Your GEO information', 'wp-bannerize')}
              defaultValue={JSON.stringify(data, null, 2)}
              validationError={__('Invalid JSON', 'wp-bannerize')}
              formatOnBlur
              autosize
              minRows={4}
            />
          )}
        </Stack>
      </Fieldset>
    </Stack>
  );
}
