/**
 * Copyright (C) 2019-2021 Carl Kittelberger <icedream@icedream.pw>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

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>
    </>
  );
}
