import { useEffect, useState } from "react";

import silly from "./assets/silly.png";
import Entry from "./Entry";

export type Entry = { id: number; name: string; progress: number };
type State = Entry[];

const current = JSON.parse(window.localStorage.getItem("state") ?? "[]") as State;

export default function App() {
  const [guyVal, setGuy] = useState("");
  const [state, setState] = useState<State>(current);

  const addGuy = () => {
    setState((s) => {
      const newId = Math.random() * Number.MAX_SAFE_INTEGER;
      const newState = [{ id: newId, name: guyVal, progress: 0 }, ...s];
      return newState.sort((a, b) => {
        if (a.name === b.name) {
          return a.id - b.id;
        } else {
          return a.name < b.name ? -1 : 1;
        }
      });
    });
    setGuy("");
  };

  useEffect(() => {
    window.localStorage.setItem("state", JSON.stringify(state));
  }, [state]);

  useEffect(() => {
    const handler = (e: { key: string }) => {
      if (e.key === "Enter" && guyVal !== "") {
        addGuy();
      }
    };

    document.addEventListener("keydown", handler);

    return () => {
      document.removeEventListener("keydown", handler);
    };
  }, [addGuy]);

  return (
    <>
      <h1>
        <img src={silly} width="200" height="200" alt="Silly kitty cat with tongue out" />
        Silly Task Tracker
        <img src={silly} width="200" height="200" alt="Silly kitty cat with tongue out" />
      </h1>
      <label htmlFor="add">Add New Task</label>
      <input
        id="add"
        value={guyVal}
        onChange={(e) => setGuy(e.target.value)}
        type="text"
        placeholder="homework"
      />
      <button disabled={guyVal === ""} onClick={addGuy}>
        Add
      </button>
      <div className="list">
        {state.map((e, i) => (
          <Entry
            key={e.id}
            onDelete={() => setState((s) => s.filter((_, j) => j !== i))}
            onChange={(newVal) => setState((s) => s.with(i, { ...e, progress: newVal }))}
            {...e}
          />
        ))}
      </div>
    </>
  );
}
