import { useCallback, useState } from 'react';
import tw from 'twin.macro';
import { invoke } from '@tauri-apps/api/tauri';
import './App.css';
import { Configurator } from './configurator/configurator';
import { ButtonSwitch } from './commons/components/button';
import { fillParentCss } from './styles/fill-parent';

type Mode = 'Flowing' | 'Follow' | null;

localStorage.setItem('debug', '*');

function App() {
  const [screenshots, setScreenshots] = useState<string[]>([]);
  const [ledStripColors, setLedStripColors] = useState<string[]>([]);
  const [currentMode, setCurrentMode] = useState<Mode>(null);

  async function takeSnapshot() {
    const base64TextList: string[] = await invoke('take_snapshot');

    setScreenshots(base64TextList.map((text) => `data:image/webp;base64,${text}`));
  }

  const getLedStripColors = useCallback(async () => {
    setLedStripColors(await invoke('get_led_strip_colors'));
  }, []);

  const switchCurrentMode = useCallback(
    async (targetMode: Mode) => {
      console.log(targetMode, currentMode, currentMode === targetMode);
      if (currentMode === targetMode) {
        await invoke('play_mode', { targetMode: 'None' });
        setCurrentMode(null);
      } else {
        await invoke('play_mode', { targetMode });
        setCurrentMode(targetMode);
      }
      console.log(targetMode, currentMode, currentMode === targetMode);
    },
    [currentMode, setCurrentMode],
  );

  return (
    <div css={[fillParentCss]} tw="box-border flex flex-col">
      <div tw="flex justify-between">
        {ledStripColors.map((it) => (
          <span tw="h-8 flex-auto" style={{ backgroundColor: it }}></span>
        ))}
      </div>

      <div tw="flex gap-1 justify-center w-screen overflow-hidden">
        {screenshots.map((screenshot) => (
          <div tw="flex-auto">
            <img src={screenshot} />
          </div>
        ))}
      </div>

      <div tw="flex gap-5 justify-center">
        <ButtonSwitch onClick={() => takeSnapshot()}>Take Snapshot</ButtonSwitch>
        <ButtonSwitch onClick={() => getLedStripColors()}>Get Colors</ButtonSwitch>
        <ButtonSwitch onClick={() => switchCurrentMode('Flowing')}>
          Flowing Light
        </ButtonSwitch>
        <ButtonSwitch onClick={() => switchCurrentMode('Follow')}>Follow</ButtonSwitch>
      </div>

      <div css={[fillParentCss]}>
        <Configurator />
      </div>
    </div>
  );
}

export default App;
