import { Alert, Grow, Rating, Typography } from "@mui/material";
import "./App.css";
import ButtonRow, { ActionProps } from "./components/ButtonRow";
import ReviewField, { ReviewFieldProps } from "./components/ReviewField";
import { useState } from "react";

function App() {
  const [rating, setNewRating] = useState<number | null>(0);
  const [showAlert, changeAlert] = useState(false);
  const [alertText, changeAlertText] = useState("");

  const fields: ReviewFieldProps[] = [
    {
      name: "Name",
      dynamicState: useState("")
    },
    {
      name: "Title",
      dynamicState: useState("")
    },
    {
      name: "Content",
      dynamicState: useState("")
    }
  ];

  const clearValues = () => {
    fields.forEach((field) => {
      field.dynamicState[1]("");
    });

    setNewRating(null);
  }

  const showThenHide = async () => {
    await fetch("http://localhost:8080/post", {
      method: "POST",
      body: JSON.stringify({
        rating: rating,
        username: fields[0].dynamicState[0],
        title: fields[1].dynamicState[0],
        content: fields[2].dynamicState[0]
      })
    })
    .then(async ({ json }) => {
      const result = await json();

      changeAlertText(result.error ? `${result.error.type}: ${result.error.message}` : `Success: ${result.message}`);
    })
    .catch((err) => changeAlertText(err.toString()));

      if (showAlert) {
        return;
      }

      changeAlert(true);

      setTimeout(() => {
        changeAlert(false);
      }, 2500);
  }

  const buttons: ActionProps[] = [
    {
      name: "Clear",
      type: "outlined",
      action: clearValues
    },
    {
      name: "Submit",
      type: "contained",
      action: showThenHide
    },
  ];

  const alert = (
    <Alert severity="info">
      {alertText}
    </Alert>
  );

  return (
    <>
      <Typography variant="h3">
        Simple Review Client
      </Typography>

      <br />

      <Rating 
        name="review-rating"
        precision={0.5}
        size="large"
        value={rating}
        onChange={(event, newRating) => {
          setNewRating(newRating);
        }}
      />

      <br />
      <br />

      <ReviewField fields={fields} />

      <br />

      <ButtonRow buttons={buttons} />

      <br />

      <Grow in={showAlert}>
        {alert}
      </Grow>
    </>
  );
}

export default App;
