import React from "react";
import LocalStorage from "@/js/Tools/LocalStorage.js";
import Icon from "@/jsx/Components/Icon.jsx";
import {__} from "@wordpress/i18n";

export default class ThemeToggle extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      theme: 'system'
    };
  }

  /**
   * Define the initial theme state
   */
  componentDidMount() {

    const lsTheme = LocalStorage.get('theme') ?? 'system';
    const theme = lsTheme === 'system' ?
      (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : lsTheme;

    // Set TailwindCSS theme
    this.setTailwindTheme(theme);

    // Set the state
    this.setState({
      theme: theme
    });

  }

  /**
   * Invert the current theme
   * @return {string}
   */
  invertedTheme() {
    return this.state.theme === 'light' ? 'dark' : 'light';
  }

  /**
   * Set TailwindCSS theme
   * @param theme
   */
  setTailwindTheme(theme) {

    theme === 'dark' ?
      document.documentElement.classList.add('dark') :
      document.documentElement.classList.remove('dark');

  }

  /**
   * Handle theme change
   */
  handleThemeChange() {

    const newTheme = this.invertedTheme();

    // Switch TailwindCSS theme
    this.setTailwindTheme(newTheme);

    // Save the theme to the local storage
    LocalStorage.set('theme', newTheme);

    // Change the state
    this.setState(
      {theme: newTheme}
    )

  }

  render() {

    return (
      <button
        className="ra-theme-toggle"
        onClick={this.handleThemeChange.bind(this)}
        title={this.state.theme === 'dark' ? __('Light mode','readabler-assistant') : __('Dark mode','readabler-assistant')}
      >
        <Icon strokeWidth={2.5}>
          {this.invertedTheme()}
        </Icon>
      </button>
    );

  }

}
