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

export const TicketRespond = ({
  ticketKey,
  questionKey,
  customer,
  supportUnit,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      content: "",
      title: "",
      image: [],
    },
    validationSchema: Yup.object({
      content: Yup.string().required("این فیلد اجباری است!"),
      title: 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 direction="column" gap={SPACING.TINY}>
      <Grid>
        <TextField
          id="title"
          label="عنوان پاسخ"
          variant="outlined"
          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
          }
        />
      </Grid>
      <Grid>
        <TextField
          multiline
          rows={4}
          fullWidth
          id="content"
          label="توضیحات"
          variant="outlined"
          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>
      <Grid>
        <Button
          fullWidth
          variant="contained"
          disabled={!formik.isValid}
          onClick={() => {
            dispatch(LOADING_START());
            const respondType = customer
              ? ticketCreateTicket({
                  ticket_key: ticketKey,
                  support_unit: supportUnit,
                  title: formik.values.title,
                  content: formik.values.content,
                  image: formik.values.image,
                })
              : ticketRespondTicket({
                  title: formik.values.title,
                  content: formik.values.content,
                  ticket_key: ticketKey,
                  // question_key: questionKey,
                  image: formik.values.image,
                });
            dispatch(respondType).then((r) => {
              dispatch(LOADING_END());
              if (r.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "مشکلی پیش آمده است!",
                  severity: "error",
                });
              } else {
                dispatch(ticketGetCreatedTickets());
                dispatch(ticketGetOperatorTickets());
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};

TicketRespond.propTypes = {
  ticketKey: PropTypes.any,
  questionKey: PropTypes.any,
  customer: PropTypes.any,
  supportUnit: PropTypes.any,
};
