import { FC, useEffect, useState } from 'react';
import { Element } from '../types';
import ElementView from './ElementView';
import Dialog from './Dialog';
import ElementCreator from './ElementCreator';
import { userStore } from '../stores';
import toast from 'react-hot-toast';

const ElementList: FC = () => {
  const [elements, setElements] = useState<Element[]>([]);
  const [elementCreatorVisible, setElementCreatorVisible] =
    useState<boolean>(false);
  const [creatorFirstElementId, setCreatorFirstElementId] = useState<
    number | undefined
  >(undefined);
  const [creatorSecondElementId, setCreatorSecondElementId] = useState<
    number | undefined
  >(undefined);
  const user = userStore((store) => store.user);

  useEffect(() => {
    const initialElements: number[] = [1, 2, 3, 4];

    const elementStateString = localStorage.getItem('elementState');
    if (elementStateString != null) {
      setElements(JSON.parse(elementStateString));
      return;
    }

    const fetchElements = async () => {
      const elems: Element[] = [];

      for (const elemId of initialElements) {
        const response = await fetch(`/api/element/${elemId}`);
        const elem: Element = await response.json();
        elems.push(elem);
      }

      localStorage.setItem('elementState', JSON.stringify(elems));
      setElements(elems);
    };

    fetchElements().catch(console.error);
  }, []);

  useEffect(() => {
    if (elements.length != 0) {
      localStorage.setItem('elementState', JSON.stringify(elements));
    }
  }, [elements]);

  const createOnElementCombine = (firstElementId: number) => {
    return async (secondElementId: number) => {
      const combineResponse = await fetch(
        `/api/element/combine?firstElementId=${firstElementId}&secondElementId=${secondElementId}`,
      );
      if (combineResponse.status == 404) {
        console.log("Element doesn't exist");
        if (!user) {
          toast("You have discovered a new element but need to log in to name it");
          return;
        }
        setCreatorFirstElementId(firstElementId);
        setCreatorSecondElementId(secondElementId);
        setElementCreatorVisible(true);
        return;
      }

      const newElem: Element = await combineResponse.json();
      if (elements.find((e) => e.id == newElem.id)) {
        toast(`You have already discovered ${newElem.name}`);
        return;
      }
      setElements((elems) => elems.concat(newElem));
    };
  };

  return (
    <div className="p-3 flex gap-3">
      {elements.map((elem) => (
        <ElementView
          key={elem.id}
          interactive={true}
          isPreview={false}
          element={elem}
          onElementCombine={createOnElementCombine(elem.id)}
        />
      ))}
      <Dialog
        visible={elementCreatorVisible}
        closeDialog={() => {
          setElementCreatorVisible(false);
        }}>
        <ElementCreator
          firstElementId={creatorFirstElementId}
          secondElementId={creatorSecondElementId}
          closeDialog={() => setElementCreatorVisible(false)}
        />
      </Dialog>
    </div>
  );
};

export default ElementList;
