import TextField from "@mui/material/TextField";
import MenuItem from "@mui/material/MenuItem";
import Button from "@mui/material/Button";
import { DialogTitle, InputAdornment } from "@mui/material";
import { useState, useEffect, useRef } from "react";
import { createFormData } from "../utils/formUtils";
import { addSupply, sendCsvFile } from "../services/supplies";
import { useHistory } from "react-router-dom";
import { styled } from "@mui/material/styles";
import IconButton from "@mui/material/IconButton";
import UploadFileIcon from "@mui/icons-material/UploadFile";
import AddIcon from "@mui/icons-material/Add";
import {
  getProviders,
  addPriceToProviderById,
  addProvider,
} from "../services/providers";
import { getCategories, addCategory } from "../services/categories";
import { useParams } from "react-router-dom";

//sockets
import io from "socket.io-client";

//pop up
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";

const API = process.env.REACT_APP_API;

const Input = styled("input")({
  display: "none",
});

export default function FormSupply() {
  //popUp
  const [openC, setOpenC] = useState(false);
  const [openP, setOpenP] = useState(false);

  const handleClickOpen = () => {
    setOpenC(true);
  };

  const handleClose = () => {
    setOpenC(false);
  };

  const handleClickOpenP = () => {
    setOpenP(true);
  };

  const handleCloseP = () => {
    setOpenP(false);
  };

  //end PopUp

  // history
  const history = useHistory();

  const [csv, setCsv] = useState([]);

  // form state
  const [form, setForm] = useState({
    name: "",
    description: "",
    category: "",
    providers: "",
    unity: "",
    imageSupply: "",
    code: "",
    location: "",
  });

  const [image, setImage] = useState({ preview: "", raw: "" });

  // handlers

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });
  };

  const handleImage = (e) => {
    if (e.target.files.length) {
      // console.log(e.target.files[0]);
      setImage({
        preview: URL.createObjectURL(e.target.files[0]),
        raw: e.target.files[0],
      });
    }

    setForm({
      ...form,
      imageSupply: e.target.files[0],
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // console.log('form', form);
    // console.log('csv', cvs);
    // console.log('formProvider', formProvider);

    if (!csv.name) {
      const formData = createFormData(form);
      console.log("formData desde formSupply", formData);
      addSupplyToServer(formData);

      // reset states
      setForm({
        name: "",
        description: "",
        category: "",
        providers: "",
        imageSupply: "",
        code: "",
        location: "",
        quantity: "",
        amount: "",
      });

      setImage({ preview: "", raw: "" });
    } else {
      const formData = new FormData();
      formData.append("file", csv);
      const res = await sendCsvFile(formData);
      console.log(res);
      if (res !== null) {
        history.push("/supplies");
      }
    }
  };

  //==============================================================================

  //services

  // add supply
  const addSupplyToServer = async (form) => {
    console.log("form VERVER", form);
    const response = await addSupply(form);
    console.log("response", response);
    if (response !== null) {
      history.push("/supplies");
    }
  };

  //PROVIDERS

  const socketRef = useRef();
  const [providers, setProviders] = useState([]);
  const [newProvider, setNewProvider] = useState({
    name: "",
  });

  const handleChangeProviders = (event) => {
    setNewProvider({
      ...newProvider,
      [event.target.name]: event.target.value,
    });
  };

  const handleSubmitProvider = (event) => {
    event.preventDefault();
    console.log(newProvider.name);
    addProvider({
      name: newProvider.name,
      description: "",
    });

    handleCloseP();
  };

  //Crea el array de proveedores y queda a la escucha de nuevos posts

  useEffect(() => {
    socketRef.current = io.connect(`${API}`);

    socketRef.current.on("listenProviders", async () => {
      loadProviders();
    });

    const loadProviders = async () => {
      const providers = await getProviders();
      setProviders(providers);
      console.log(providers);
    };
    loadProviders();
  }, []);

  //CATEGORIES

  const [categories, setCategories] = useState([]);
  const [newCategory, setNewCategory] = useState({
    nombre: "",
  });

  const handleChangeCategories = (event) => {
    setNewCategory({
      ...newCategory,
      [event.target.name]: event.target.value,
    });
  };

  const handleSubmitCategory = (event) => {
    event.preventDefault();
    console.log(newCategory.nombre);
    addCategory({
      name: newCategory.nombre,
      description: "Es una descripción",
    });
    handleClose();
  };

  //Crea el array de categorías y queda a la escucha de nuevos posts

  useEffect(() => {
    socketRef.current = io.connect(`${API}`);

    socketRef.current.on("listenCategories", async () => {
      loadCategories();
    });

    const loadCategories = async () => {
      const categories = await getCategories();
      setCategories(categories);
      console.log(categories);
    };
    loadCategories();
  }, []);

  const handleSubmitTest = async (e) => {
    e.preventDefault();
    console.log("test");
    console.log(form);
  };

  return (
    <>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-around",
          width: "60vw",
          background: " #23282C",
          padding: "5ch",
          height: "850px",
        }}
      >
        <div
          style={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            alignItems: "center",
            height: "400px",
          }}
        >
          <div
            style={{
              width: "50%",
              flexDirection: "column",
              height: "100%",
              display: "flex",
              justifyContent: "space-between",
            }}
          >
            <TextField
              name="name"
              className="textField"
              label="Nombre"
              variant="outlined"
              onChange={handleChange}
              style={{ width: "90%" }}
            />
            <TextField
              className="textField"
              name="location"
              label="Ubicación"
              variant="outlined"
              onChange={handleChange}
              type="text"
              style={{ width: "90%" }}
            />
            <TextField
              name="code"
              className="textField"
              label="Código"
              variant="outlined"
              onChange={handleChange}
              style={{ width: "90%" }}
            />
            <div
              style={{ display: "flex", flexDirection: "row", width: "100%" }}
            >
              <TextField
                className="textField"
                name="category"
                select
                label="Categoría"
                value={form.category}
                onChange={handleChange}
                style={{ width: "100%" }}
              >
                {categories.map((option) => (
                  <MenuItem key={option._id} value={option._id}>
                    <p> {option.name} </p>
                  </MenuItem>
                ))}
              </TextField>

              <Button
                className="btn-hover"
                variant="contained"
                sx={{ background: "#3082AA !important" }}
                onClick={handleClickOpen}
              >
                <AddIcon />
              </Button>
            </div>

            <TextField
              className="textField"
              name="unity"
              label="Unidad de medida"
              type="string"
              variant="outlined"
              style={{ width: "90%" }}
              onChange={handleChange}
            />
          </div>
          <div
            style={{
              width: "50%",
              display: "flex",
              justifyContent: "center",
            }}
          >
            <div
              style={{
                display: "flex",
                justifyContent: "center",
                overflow: "hidden",
                borderRadius: "50%",
                width: "200px",
                height: "200px",
              }}
            >
              <Button
                style={{
                  padding: "0",
                }}
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  document.getElementById("imageSupply").click();
                }}
              >
                <img
                  src={
                    image.preview
                      ? image.preview
                      : "https://thealmanian.com/wp-content/uploads/2019/01/product_image_thumbnail_placeholder.png"
                  }
                  alt="preview"
                  style={{
                    width: "100%",
                    objectFit: "fill",
                  }}
                />
              </Button>
              <input
                type="file"
                id="imageSupply"
                name="imageSupply"
                accept="image/*"
                style={{ display: "none" }}
                onChange={handleImage}
              />
            </div>
          </div>
        </div>
        <div style={{ display: "flex", width: "90%" }}>
          <TextField
            className="textField"
            name="providers"
            style={{ width: "50%" }}
            select
            value={form.providers}
            onChange={handleChange}
            label="Proveedor"
          >
            {providers.map((item) => (
              <MenuItem key={item._id} value={item._id}>
                {item.name}
              </MenuItem>
            ))}
          </TextField>
          <Button
            className="btn-hover"
            variant="contained"
            sx={{ background: "#3082AA !important" }}
            onClick={handleClickOpenP}
          >
            <AddIcon />
          </Button>
        </div>

        <TextField
          className="textField"
          name="quantity"
          label="Cantidad"
          variant="outlined"
          onChange={handleChange}
          type="number"
          style={{ width: "45%" }}
        />

        <TextField
          className="textField"
          name="amount"
          label="Precio"
          variant="outlined"
          onChange={handleChange}
          type="number"
          style={{ width: "45%" }}
        />

        <TextField
          className="textField"
          name="description"
          label="Descripcion"
          variant="outlined"
          onChange={handleChange}
          style={{ marginBottom: "2ch" }}
          multiline
          inputProps={{
            style: {
              height: 80,
            },
          }}
        />
      </div>
      <div
        style={{
          display: "flex",
          justifyContent: "flex-end",
          marginTop: "3ch",
          width: "66vw",
        }}
      >
        <label htmlFor="icon-button-file">
          <Input
            id="icon-button-file"
            type="file"
            name="file"
            onChange={(e) => {
              const file = e.target.files[0];
              setCsv(file);
            }}
          />
          <IconButton color="primary" aria-label="upload file" component="span">
            <UploadFileIcon />
          </IconButton>
        </label>

        <Button onClick={handleSubmitTest}>test</Button>

        <Button
          type="submit"
          variant="contained"
          color="primary"
          onClick={handleSubmit}
          sx={{ ml: "20px" }}
        >
          Agregar
        </Button>

        {/* POP UP DIALOG  CATEGORY */}
        <Dialog open={openC} onClose={handleClose}>
          <DialogTitle>Nueva Categoría</DialogTitle>
          <DialogContent>
            <TextField
              autoFocus
              name="nombre"
              margin="dense"
              id="category"
              label="Categoría"
              onChange={handleChangeCategories}
              type="text"
              fullWidth
              variant="standard"
            />
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose}>Cancelar</Button>
            <Button onClick={handleSubmitCategory}>Confirmar</Button>
          </DialogActions>
        </Dialog>

        {/* POP UP DIALOG  PROVIDERS */}
        <Dialog open={openP} onClose={handleCloseP}>
          <DialogTitle>Nuevo Proveedor</DialogTitle>
          <DialogContent>
            <TextField
              autoFocus
              name="name"
              margin="dense"
              id="provider"
              label="Proveedor"
              onChange={handleChangeProviders}
              type="string"
              fullWidth
              variant="standard"
            />
          </DialogContent>

          <DialogActions>
            <Button onClick={handleCloseP}>Cancelar</Button>
            <Button onClick={handleSubmitProvider}>Confirmar</Button>
          </DialogActions>
        </Dialog>
      </div>
    </>
  );
}
