import Button from "@mui/material/Button";
import * as React from "react";
import axios from "axios";
import { useEffect, useState } from "react";
import List from "@mui/material/List";
import {
  Container,
  ListItem,
  ListItemButton,
  ListItemText,
} from "@mui/material";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import Grid from "@mui/material/Grid";
import SelectField from "../../components/SelectField";
import { useForm } from "../../actions/useForm";
import { Form } from "../../components/EmailForm";
import { fetchTypes } from "../../helpers/types";
import { fetchSigns } from "../../helpers/signs";
import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import ErrorBox from "../../components/errorBox";

export default function ImportEmailPage() {
  const [chosenFiles, setChosenFiles] = useState([]);
  const [selectedType, setSelectedType] = useState(1);
  const [selectedSigns, setSelectedSigns] = useState([]);
  const [signs, setSigns] = useState([]);
  const [types, setTypes] = useState([]);
  const [invalidFiles, setInvalidFiles] = useState([]);
  const [error, setError] = useState();

  useEffect(() => {
    fetchTypes().then((data) => setTypes(data));
    fetchSigns().then((data) => setSigns(data));
  }, []);

  function validate() {
    if (selectedType == 1 && selectedSigns.length > 0) {
      setError("Legitimate type cannot have signs!");
      return false;
    } else if (selectedType > 1 && selectedSigns.length == 0) {
      setError("Phishing e-mail has to own at least one sign!");
      return false;
    }
    return true;
  }

  function handleImport() {
    if (!validate()) return;

    let invalFiles = [];

    chosenFiles.forEach((chFile) => {
      const reader = new FileReader();
      reader.onload = async (e) => {
        const text = e.target.result;

        await axios
          .post("http://localhost:8000/emails/import/", {
            text: text,
            type: selectedType,
            sign: selectedSigns,
          })
          .catch((err) => {
            invalFiles.push(chFile);
          });
      };
      reader.readAsText(chFile);
    });
    setChosenFiles(invalFiles);
    setInvalidFiles(invalFiles);
  }

  const chooseFiles = async (e) => {
    e.preventDefault();
    const selectedFiles = Array.from(e.target.files);

    const nonDuplicated = selectedFiles.filter(
      (file) => chosenFiles.indexOf(file) === -1
    );
    setChosenFiles([...chosenFiles, ...nonDuplicated]);
  };

  function handleCancelFile(file) {
    const nonRemovedFiles = chosenFiles.filter((filename) => filename !== file);

    setChosenFiles(nonRemovedFiles);
  }

  function handleTypeChange(e) {
    const type_id = e.target.value;

    if (type_id === 1 && selectedSigns.length > 0) return;
    setSelectedType(e.target.value);
  }

  function handleSignChange(e) {
    setSelectedSigns(e.target.value);
  }

  return (
    <React.Fragment>
      <Box sx={{ position: "relative" }}>
        <ErrorBox severity="error" msg={error} />
      </Box>
      <Grid container sx={{ mt: "10%" }} spacing={3} justifyContent="center">
        <Grid item container direction="column" xs={12} sm={6}>
          <Button
            variant="contained"
            component="label"
            sx={{ alignSelf: "center" }}
          >
            Add files
            <input
              type="file"
              hidden
              multiple
              accept=".txt"
              onChange={chooseFiles}
            />
          </Button>
        </Grid>

        <Grid item container xs={12} sm={6}>
          <List
            sx={{
              width: "100%",
              maxWidth: 360,
              bgcolor: "background.paper",
            }}
          >
            {chosenFiles.map((file, index) => {
              return (
                <ListItem key={index}>
                  <ListItemButton onClick={(e) => handleCancelFile(file)}>
                    <RemoveCircleOutlineIcon />
                  </ListItemButton>
                  <ListItemText
                    sx={invalidFiles.indexOf(file) !== -1 && { color: "red" }}
                  >
                    {file.name}
                  </ListItemText>
                </ListItem>
              );
            })}
          </List>
        </Grid>
        <Grid item container xs={12} spacing={5} mt={5}>
          {/* SelectField field for selecting type of email */}
          <Grid item xs={12} sm={6}>
            <SelectField
              name="type"
              label="Type"
              value={selectedType}
              onChange={handleTypeChange}
              options={types}
              type={"type"}
            />
          </Grid>
          <Grid item xs={12} sm={6}>
            {/* SelectField field for multi selecting signs of emails */}
            <SelectField
              name="sign"
              label="Signs"
              value={selectedSigns}
              onChange={handleSignChange}
              options={signs}
              multiple={true}
              type={"sign"}
            />
          </Grid>
        </Grid>
        <Grid item container direction="column" xs={12}>
          <Button
            variant="contained"
            component="label"
            onClick={handleImport}
            sx={{ alignSelf: "center" }}
          >
            Import
          </Button>
        </Grid>
      </Grid>
    </React.Fragment>
  );
}
