import { useEffect, useReducer } from "react";
import "./App.css";
import { Equipment } from "./components/Equipment";
import { reducer, withLoadingAction } from "./lib/state";
import type { ItemId } from "./lib/types";
import { SourceList } from "./components/SourceList";

function App() {
  const [state, dispatch] = useReducer(withLoadingAction(reducer), "loading");

  useEffect(() => {
    if (state === "loading") {
      console.log("Loading state...");
      // TODO: Parse with Zod?
      const stateValue = localStorage.getItem("state");
      if (stateValue) {
        dispatch({
          action: "loadState",
          state: JSON.parse(stateValue),
        });
      } else {
        dispatch({
          action: "loadState",
          state: {
            equipedItems: [{ id: 219309 as ItemId, quality: "champion" }],
            bisList: [],
          },
        });
      }
    } else {
      console.log("Saving state...");
      localStorage.setItem("state", JSON.stringify(state));
    }
  }, [state]);

  if (state === "loading") {
    return <div>Loading...</div>;
  }

  return (
    <>
      <h1>WoW Gear Finder</h1>
      <Equipment
        state={state}
        onEquip={(item) => dispatch({ action: "equipItem", item })}
        onUnequip={(item) => dispatch({ action: "unequipItem", item })}
      />
      <SourceList state={state} />
    </>
  );
}

export default App;
