import React, { useEffect } from 'react';
// import useSWR from 'swr';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  Button,
  // Spinner
} from 'react-bootstrap';
import useSWR from 'swr';
import { FormattedMessage } from 'react-intl';
import { fetchJson } from '../util/api';

let darkToggleAnimationTimer = null;

function triggerDarkToggleAnimation() {
  document.documentElement.setAttribute('data-toggled-dark', 'true');
  if (darkToggleAnimationTimer !== null) {
    clearTimeout(darkToggleAnimationTimer);
  }
  darkToggleAnimationTimer = setTimeout(() => {
    document.documentElement.removeAttribute('data-toggled-dark');
  }, 1200);
}

export default function DarkToggler() {
  const {
    data, error, isValidating, mutate,
  } = useSWR('/api/user');

  let enableDark = false;
  let isLoading = false;

  if (isValidating || !data) {
    isLoading = true;
  }
  if (error) {
    console.warn(error);
    isLoading = false;
  } else if (data) {
    enableDark = data.enableDark;
  }

  useEffect(() => {
    if (!isLoading) {
      console.info('enable dark:', enableDark);
      if (enableDark) {
        document.documentElement.setAttribute('data-enable-dark', 'true');
      } else {
        document.documentElement.removeAttribute('data-enable-dark');
      }
    }
  });

  return (
    <>
      <Button
        onClick={async () => {
          const { enableDark: newEnableDark } = await fetchJson('/api/toggleDark');
          triggerDarkToggleAnimation();
          mutate({ enableDark: newEnableDark }, true);
        }}
        disabled={isLoading}
        variant="outline-secondary"
        active={!enableDark}
      >
        {/*
         isLoading
           ? (
             <Spinner animation="border" role="status" size="sm">
               <span className="sr-only">
                 <FormattedMessage
                   id="DarkToggler.loading"
                   defaultMessage="Loading…"
                 />
               </span>
             </Spinner>
           )
           : ''
        */}
        <FontAwesomeIcon icon={[enableDark ? 'far' : 'fa', 'lightbulb']} />
        <span className="sr-only">
          <FormattedMessage
            id="DarkToggler.screenReaderText"
            defaultMessage="Toggle dark mode"
            description="Screen reader description of the dark mode toggle button"
          />
        </span>
      </Button>
    </>
  );
}
