'use client'
import React from "react";
import styles from "@/styles/dev-tools.module.css"
import { IconButton, Snackbar, SnackbarCloseReason, Typography } from "@mui/material"
import CloseIcon from '@mui/icons-material/Close';
import { Card, Combo, EditorMode, Unit } from "@/types/dev-tools";
import { EditorContext } from "@/contexts/EditorContext";
import LeftMenu from "@/components/dev-tools/LeftMenu";
import { useEditor } from "@/hooks/useEditor";
import Editor from "@/components/dev-tools/Editor";

export default function Page(){
  const [currentRecordNum, setCurrentRecordNum] = React.useState<number>(0);
  const [currentDataId, setCurrentDataId] = React.useState<string>("");
  const [editorMode, setEditorMode] = React.useState<EditorMode>("insert");
  const [cards, setCards] = React.useState<Card[] | null>(null);
  const [currentCombos, setCurrentCombos] = React.useState<Combo[] | null>(null);
  const [units, setUnits] = React.useState<Unit[] | null>(null);
  const [error, setError] = React.useState<string | null>(null);
  const [open, setOpen] = React.useState<boolean>(false);
  
  const changeCurrentRecordNum = (n: number) => setCurrentRecordNum(n)
  const changeCurrentDataId = (id: string) => setCurrentDataId(id)
  const changeEditorMode = (m: string) =>{
    if(m !== "insert" && m !== "update") return
    setEditorMode(m)
  } 
  const changeError = (e: string) => setError(e);

  React.useEffect(() => {
    const getCards = async () => {
      try{
        // fetch our db
        const res = await fetch("/api/dev/vor/cards", {
          method: "GET",
        })
        const body = await res.json()
        if(!res.ok){
          console.error("Could not get vor cards:", body)
          setCards(null);
        } else{
          setCards(body)
        }
      }catch (error) {
        console.error("Could not get vor cards:", error)
        setCards(null);
      }
    }
    const getUnits = async () => {
      try{
        // fetch our db
        const res = await fetch("/api/dev/vor/units", {
          method: "GET",
        })
        const body = await res.json()
        if(!res.ok){
          console.error("Could not get vor units:", body)
          setUnits(null);
        } else{
          setUnits(body)
        }
      }catch (error) {
        console.error("Could not get vor units:", error)
        setUnits(null);
      }
    }
    getCards();
    getUnits();
  }, [])

  React.useEffect(() => {
    const getCombos = async () => {
      // first check if the user has unconfirmed changes, if not then go for the query
      try{
        const res = await fetch(`/api/dev/vor/${currentDataId}/combos`, {
          method: "GET",
        })
        const body = await res.json();
        if(res.ok){
          setCurrentCombos(body)
        }else{
          setCurrentCombos(null)
          console.error("Failed to get combos for:", body)
        }
      } catch(error){
        setCurrentCombos(null)
        console.error("Could not get combos for:", error)
      }
    }

  },[currentDataId])

  const handleClose = (
    event: React.SyntheticEvent | Event,
    reason?: SnackbarCloseReason,
  ) => {
    if (reason === 'clickaway') {
      return;
    }

    setOpen(false);
  };

  const action = (
    <React.Fragment>
      <Typography>
        {error}
      </Typography>
      <IconButton
        size="small"
        aria-label="close"
        color="inherit"
        onClick={handleClose}
      >
        <CloseIcon fontSize="small" />
      </IconButton>
    </React.Fragment>
  );


  return (
    <EditorContext.Provider value={{
      currentRecordNum,
      currentDataId,
      editorMode,
      error,
      cards,
      units,
      currentCombos,

      changeCurrentRecordNum,
      changeCurrentDataId,
      changeEditorMode,
      changeError
    }}>
      <div className={styles.maincontainer}>
        <div className={styles.leftmenucontainer}>
          <LeftMenu />
        </div>
        <div className={styles.editorcontainer}>
          <Editor />
        </div>
      </div>
      {error && <Snackbar
        open={open}
        autoHideDuration={6000}
        onClose={handleClose}
        action={action}
      />}
    </EditorContext.Provider>
  )
}

