import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import React, { useContext, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { SPACING } from "../../../../data/spacing";
import { Yup } from "../../../../lib/yup/yup";
import { fixBase64 } from "../../../../utils/toBase64";
import { PropTypes } from "prop-types";
import { useDispatch } from "react-redux";
import { slaughterNewComplaint } from "../../services/slaughter-new-complaint";
import { AppContext } from "../../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { slaughterGetRegisteredComplaints } from "../../services/slaughter-get-registered-complaints";
import { slaughterGetComplaints } from "../../services/slaughter-get-complaints";

export const SlaughterHouseNewComplaint = ({ barKey, role }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [topic, setTopic] = React.useState(10);

  const [complaintImages, setComplaintImages] = React.useState([]);
  const [complaintImagesBase64, setComplaintImagesBase64] = React.useState([]);

  const complaintImageHandler = (imageList, addUpdateIndex) => {
    setComplaintImages(imageList);
    setComplaintImagesBase64(imageList.map((img) => fixBase64(img.data_url)));
  };

  const isFormValid = (topic) => {
    switch (topic) {
      case 10:
        return (
          formik2.isValid && formik.isValid && complaintImagesBase64.length
        );
      default:
        return formik.isValid && complaintImagesBase64.length;
    }
  };

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

  const formik = useFormik({
    initialValues: {
      description: "",
    },
    validationSchema: Yup.object({
      description: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را پر کنید!"),
    }),
  });

  const formik2 = useFormik({
    initialValues: {
      looses: "",
    },
    validationSchema: Yup.object({
      looses: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
    formik2.validateForm();
  }, []);

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      direction="column"
      flex="1"
      height="100%"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        <FormControl fullWidth>
          <InputLabel id="demo-simple-select-label">موضوع</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={topic}
            label="موضوع"
            onChange={handleChange}
          >
            <MenuItem value={10}>مغایرت درصد تلفات با واقعیت</MenuItem>
            <MenuItem value={20}>دیگر</MenuItem>
          </Select>
        </FormControl>

        {topic === 10 && (
          <TextField
            id="looses"
            label="درصد تلفات"
            variant="outlined"
            sx={{ width: "100%", height: "100%" }}
            value={formik2.values.looses}
            error={
              formik2.touched.looses ? Boolean(formik2.errors.looses) : null
            }
            onChange={formik2.handleChange}
            onBlur={formik2.handleBlur}
            helperText={
              formik2.touched.looses && Boolean(formik2.errors.looses)
                ? formik2.errors.looses
                : null
            }
          />
        )}

        <TextField
          id="description"
          label="توضیحات"
          multiline
          rows={5}
          variant="outlined"
          sx={{ width: "100%", height: "100%" }}
          value={formik.values.description}
          error={
            formik.touched.description
              ? Boolean(formik.errors.description)
              : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.description && Boolean(formik.errors.description)
              ? formik.errors.description
              : null
          }
        />

        <Typography>پیوست تصویر</Typography>
        <Grid mb={SPACING.SMALL}>
          <ImageUpload
            id="image"
            onChange={complaintImageHandler}
            images={complaintImages}
            maxNumber={4}
            title={"بارگذاری سند"}
            value={formik.values.image}
            error={formik.touched.image ? Boolean(formik.errors.image) : null}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.image && Boolean(formik.errors.image)
                ? formik.errors.image
                : null
            }
          />
        </Grid>
      </Grid>
      <Button
        fullWidth
        variant="contained"
        disabled={!isFormValid(topic)}
        onClick={() => {
          dispatch(LOADING_START());
          dispatch(
            slaughterNewComplaint({
              bar_key: barKey,
              image: complaintImagesBase64,
              title: topic === 10 ? " مغایرت درصد تلفات با واقعیت" : "دیگر",
              description: formik.values.description,
              percent: formik2.values?.looses ? formik2.values?.looses : null,
              role: role,
            })
          ).then((r) => {
            dispatch(LOADING_END());
            if (r.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مشکلی پیش آمده است",
                severity: "error",
              });
            } else {
              dispatch(slaughterGetComplaints());
              dispatch(slaughterGetRegisteredComplaints());
              dispatch(DRAWER({ right: false, bottom: false, content: null }));
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد!",
                severity: "success",
              });
            }
          });
        }}
      >
        ثبت اطلاعات
      </Button>
    </Grid>
  );
};

SlaughterHouseNewComplaint.propTypes = {
  barKey: PropTypes.any,
  role: PropTypes.any,
};
