import * as React from "react";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import CssBaseline from "@mui/material/CssBaseline";
import Divider from "@mui/material/Divider";
import Drawer from "@mui/material/Drawer";
import IconButton from "@mui/material/IconButton";
import InboxIcon from "@mui/icons-material/MoveToInbox";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import MailIcon from "@mui/icons-material/Mail";
import MenuIcon from "@mui/icons-material/Menu";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import {
  FormControl,
  InputAdornment,
  InputLabel,
  MenuItem,
  Select,
  TextField,
} from "@mui/material";
import Grid from "@mui/material/Grid";
import Container from "@mui/material/Container";
import Paper from "@mui/material/Paper";
import CheckIcon from "@mui/icons-material/Check";
import TypeTable from "../../components/tables/TypeTable";
import SignTable from "../../components/tables/SignTable";
import { useEffect, useRef, useState } from "react";
import axios from "axios";
import EmailTable from "../../components/tables/EmailTable";
import Button from "@mui/material/Button";

function SignSelect(typeID) {
  const [types, setTypes] = React.useState([]);
  const [selectedType, setSelectedType] = React.useState(typeID.typeID);

  const handleChange = (event) => {
    setSelectedType(event.target.value);
  };

  useEffect(() => {
    setSelectedType(typeID.typeID);
  }, [typeID]);

  useEffect(() => {
    axios
      .get("http://localhost:8000/api/types/")
      .then((resp) => {
        setTypes(resp.data);
      })
      .catch((err) => console.log(err));
  }, []);

  return (
    <Box>
      {selectedType !== -1 ? (
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            ml: 2,
            my: 6,
            maxWidth: 150,
          }}
        >
          <FormControl fullWidth>
            <InputLabel id="type-select-input">Type</InputLabel>
            <Select
              labelId="type-select-label"
              id="type-select"
              value={selectedType}
              label="Type"
              onChange={handleChange}
            >
              {types.map((type) => {
                return (
                  <MenuItem key={type.type_id} value={type.type_id}>
                    {type.type}
                  </MenuItem>
                );
              })}
            </Select>
          </FormControl>
        </Box>
      ) : (
        <div />
      )}
    </Box>
  );
}

export default function SettingsEmailInfo({ match }) {
  const [data, setData] = useState({
    email_id: 0,
    subject: "",
    sender: "",
    recipient: "",
    date: "",
    cc: "",
    body: "",
    type: -1,
    sign: [],
  });
  const [emailStats, setEmailStats] = useState({
    occurrence: "",
    average_duration: "",
    average_correctness: "",
  });
  const firstUpdate = useRef(true);
  const typeParsed = useRef(false);

  const [signs, setSigns] = useState([]);
  const [types, setTypes] = useState([]);

  const emailId = match.params.id;
  const [selectedType, setSelectedType] = useState("");

  useEffect(() => {
    const headers = {
      "Content-Type": "application/json",
    };
    axios
      .get("http://localhost:8000/api/emails/" + emailId, {
        headers: headers,
      })
      .then(function (response) {
        setData(response.data);
      })
      .catch((err) => console.log(err));

    axios("http://localhost:8000/email-statistics/" + emailId + "/", {
      method: "POST",
      withCredentials: true,
      data: { email_id: emailId },
    }).then((res) => {
      setEmailStats(res.data);
    });
  }, [firstUpdate]);

  return (
    <Box>
      <Box sx={{ display: "flex", justifyContent: "space-evenly", mt: 5 }}>
        {Object.entries(emailStats).map(([key, value]) => (
          <Paper
            sx={{
              display: "flex",
              flexDirection: "column",
              width: 160,
              height: 100,
              alignItems: "center",
              justifyContent: "center",
              backgroundColor: "#019592",
            }}
          >
            <Typography variant="h5"> {value}</Typography>
            <Typography>{key}</Typography>
          </Paper>
        ))}
      </Box>
      {Object.entries(data).map(([key, value]) => (
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            mt: "55px",
            ml: "15px",
          }}
        >
          <Box sx={{ width: "35%", pr: "15px" }}>{key}:</Box>

          <Box sx={{ width: "65%" }}>{value}</Box>
        </Box>
      ))}

      <SignSelect typeID={data.type} />
      <SignTable emailID={emailId} />
      <Box sx={{ display: "flex", justifyContent: "center", my: 5 }}>
        <Button variant="contained">Save</Button>
      </Box>
    </Box>
  );
}
