import { useEffect, useState } from 'preact/hooks';
import type { Bar, BarConfig } from '@wutzcalc/shared';
import { api } from '../api';
import { BarPicker } from './BarPicker';
import { Sale } from './Sale';

const STORAGE_KEY = 'wutz.bar_id';

export function App() {
  const [bars, setBars] = useState<Bar[] | null>(null);
  const [barId, setBarId] = useState<number | null>(() => {
    const v = localStorage.getItem(STORAGE_KEY);
    return v ? Number(v) : null;
  });
  const [config, setConfig] = useState<BarConfig | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (barId == null) {
      api.bars().then(setBars).catch(e => setError(String(e)));
    }
  }, [barId]);

  useEffect(() => {
    if (barId == null) return;
    setConfig(null);
    api.config(barId).then(setConfig).catch(e => setError(String(e)));
  }, [barId]);

  function pick(id: number) {
    localStorage.setItem(STORAGE_KEY, String(id));
    setBarId(id);
  }

  function changeBar() {
    localStorage.removeItem(STORAGE_KEY);
    setBarId(null);
    setConfig(null);
  }

  if (error) return <div class="bar-picker"><h1>Fehler</h1><p>{error}</p><button onClick={() => location.reload()}>Neu laden</button></div>;
  if (barId == null) return <BarPicker bars={bars} onPick={pick} />;
  if (!config) return <div class="bar-picker"><p>Lade…</p></div>;
  return <Sale config={config} onChangeBar={changeBar} />;
}
