import React, { useContext, useEffect, useState } from "react";
import { styled } from "@mui/material/styles";
import Button from "@mui/material/Button";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { Grid } from "../../../../components/grid/Grid";
import { Typography } from "@mui/material";
import { useDispatch } from "react-redux";
import { cityUpdateHatchingService } from "../../services/city-update-hatching";
import { AppContext } from "../../../../contexts/AppContext";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { cityUpdateChickenBreedService } from "../../services/city-update-chicken-breen";

const VisuallyHiddenInput = styled("input")({
  clip: "rect(0 0 0 0)",
  clipPath: "inset(50%)",
  height: 1,
  overflow: "hidden",
  position: "absolute",
  bottom: 0,
  left: 0,
  whiteSpace: "nowrap",
  width: 1,
});

export const CityUpdateHatching = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [response, setResponse] = useState();
  const [tableData, setTableData] = useState();
  const handleFileUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("file", file);

    dispatch(cityUpdateHatchingService(formData))
      .unwrap()
      .then((r) => {
        setResponse(r.data);
        if (r.status === 201) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "فایل اکسل به درستی ارسال نشده است!",
            severity: "error",
          });
        }
      });
  };
  const handleUpdateChickenBreed = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("file", file);

    dispatch(cityUpdateChickenBreedService(formData))
      .unwrap()
      .then((r) => {
        if (r.status === 201) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "فایل اکسل به درستی ارسال نشده است!",
            severity: "error",
          });
        }
      });
  };
  useEffect(() => {
    const d = response?.map((item, i) => {
      return [i + 1, item];
    });
    setTableData(d);
  }, [response]);
  return (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      spacing={2}
      mb={1}
      style={{ width: "80vw" }}
    >
      <Grid
        xs={12}
        md={6}
        sm={6}
        container
        alignItems="center"
        mt={6}
        spacing={2}
        justifyContent="center"
        style={
          window.innerWidth >= 800 && {
            borderStyle: "solid",
            borderWidth: "0px 0px 0px 1px",
            borderColor: "gray",
          }
        }
      >
        <Grid>
          <Typography variant="body1" style={{ color: "gray" }}>
            آپدیت جوجه ریزی
          </Typography>
        </Grid>

        <Grid>
          <Button
            component="label"
            role={undefined}
            variant="contained"
            tabIndex={-1}
            startIcon={<CloudUploadIcon />}
          >
            آپلود فایل اکسل
            <VisuallyHiddenInput type="file" onChange={handleFileUpload} />
          </Button>
          {response?.length ? (
            <Grid container xs={12} justifyContent="start">
              <SimpleTable
                columns={["ردیف", "شناسه یکتا"]}
                name={"مرغداران ناموجود در سامانه"}
                data={tableData}
              />
            </Grid>
          ) : (
            <></>
          )}
        </Grid>
      </Grid>
      <Grid
        xs={12}
        md={6}
        sm={6}
        container
        alignItems="center"
        mt={6}
        spacing={2}
        justifyContent="center"
      >
        <Grid>
          <Typography variant="body1" style={{ color: "gray" }}>
            آپدیت نژاد
          </Typography>
        </Grid>
        <Grid>
          <Button
            component="label"
            role={undefined}
            variant="contained"
            tabIndex={-1}
            startIcon={<CloudUploadIcon />}
          >
            آپلود فایل اکسل
            <VisuallyHiddenInput
              type="file"
              onChange={handleUpdateChickenBreed}
            />
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};
