import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
} from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { fixBase64 } from "../../../../utils/toBase64";
import { ticketCreateTicket } from "../../services/ticket-create-ticket";
import { ticketGetCreatedTickets } from "../../services/ticket-get-created-tickets";

export const TicketCreate = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      title: "",
      supportUnit: "",
      content: "",
      image: [],
    },
    validationSchema: Yup.object({
      title: Yup.string().required("این فیلد اجباری است!"),
      supportUnit: Yup.string().required("این فیلد اجباری است!"),
      content: Yup.string().required("این فیلد اجباری است!"),
    }),
  });

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

  const [attachmentImages, setAttachmentImages] = useState([]);

  const attachmentsHandler = (imageList, addUpdateIndex) => {
    const base64Urls = imageList.map((image) => fixBase64(image.data_url));
    formik.setFieldValue("image", base64Urls);
    setAttachmentImages(imageList);
  };

  return (
    <Grid container justifyContent="space-between">
      <Grid container flexGrow="1" gap={SPACING.SMALL} direction="column">
        <Grid>
          <TextField
            fullWidth
            id="title"
            label="موضوع"
            value={formik.values.title}
            error={formik.touched.title ? Boolean(formik.errors.title) : null}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.title && Boolean(formik.errors.title)
                ? formik.errors.title
                : null
            }
            variant="outlined"
          />
        </Grid>
        <Grid>
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">واحد مربوطه</InputLabel>
            <Select
              fullWidth
              value={formik.values.supportUnit}
              id="supportUnit"
              label="واحد مربوطه"
              onChange={(e) => {
                formik.setFieldValue("supportUnit", e.target.value);
              }}
            >
              <MenuItem value={"CityOperator"}>شهرستان</MenuItem>
              <MenuItem value={"ProvinceOperator"}>تخصیص استان</MenuItem>
              <MenuItem value={"ProvinceInspector"}>بازرسی استان</MenuItem>
              <MenuItem value={"ProvinceFinancial"}>واحد مالی استان</MenuItem>
            </Select>
          </FormControl>
        </Grid>
        <Grid>
          <TextField
            id="content"
            label="توضیحات"
            multiline
            rows={5}
            variant="outlined"
            sx={{ width: "100%", height: "100%" }}
            value={formik.values.content}
            error={
              formik.touched.content ? Boolean(formik.errors.content) : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.content && Boolean(formik.errors.content)
                ? formik.errors.content
                : null
            }
          />
        </Grid>
        <Grid>
          <ImageUpload
            onChange={attachmentsHandler}
            images={attachmentImages}
            maxNumber={3}
            title={"افزودن پیوست"}
          />
        </Grid>
        <Button
          fullWidth
          variant="contained"
          disabled={!formik.isValid}
          onClick={() => {
            dispatch(LOADING_START());
            dispatch(
              ticketCreateTicket({
                title: formik.values.title,
                content: formik.values.content,
                support_unit: formik.values.supportUnit,
                image: formik.values.image,
              })
            ).then((r) => {
              dispatch(LOADING_END());

              if (r.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "مشکلی پیش آمده است!",
                  severity: "error",
                });
              } else {
                dispatch(ticketGetCreatedTickets());
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          ارسال تیکت
        </Button>
      </Grid>
    </Grid>
  );
};
