import React, { useState, useEffect } from 'react';
import Button from '@digigov/react-core/Button';

export const ThemeToggleButton = () => {
  const [theme, setTheme] = useState(() => {
    const currentTheme = localStorage.getItem('theme');
    const prefersScheme = window.matchMedia('(prefers-color-scheme: dark)')
      .matches
      ? 'dark'
      : 'light';
    return currentTheme || prefersScheme || 'light';
  });

  function toggleTheme() {
    if (theme === 'light') {
      setTheme('dark');
    } else {
      setTheme('light');
    }
  }
  useEffect(() => {
    localStorage.setItem('theme', theme);
    document.documentElement.className = theme;
  }, [theme]);
  useEffect(() => {
    const beforePrintListener = () => {
      document.documentElement.className = 'light';
    };
    const afterPrintListener = () => {
      document.documentElement.className =
        localStorage.getItem('theme') || theme;
    };
    window.addEventListener('beforeprint', beforePrintListener);
    window.addEventListener('afterprint', afterPrintListener);
    return () => {
      window.removeEventListener('beforeprint', beforePrintListener);
      window.removeEventListener('afterprint', afterPrintListener);
    };
  }, []);

  return (
    <Button
      onClick={toggleTheme}
      variant="link"
      role="button"
      aria-label="Αντιστροφή χρωμάτων"
    >
      Αντιστροφή χρωμάτων
    </Button>
  );
};
export default ThemeToggleButton;
