import {
  Button,
  FormControl,
  FormHelperText,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
  Grid,
} from "@mui/material";
import React, { useState, useContext } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch } from "react-redux";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { provinceNeedRequestFormService } from "../../services/province-need-request-form";
import { getSlaughtersKillRequestService } from "../../../city/services/get-slaughters-kill-request";
import { AppContext } from "../../../../contexts/AppContext";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";

export function ProvinceNeedRequestForm({ killRequestKey, quantity, item }) {
  const [isDenied, setIsDenied] = useState(false);
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();

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

  const acceptButtonText = "تایید";
  const rejectButtonText = "رد";
  const handleAccept = () => {
    const requestData = {
      state: "accepted",
      kill_request_key: killRequestKey,
    };

    if (formik.values.number) {
      requestData.quantity = formik.values.number;
    }

    if (formik.values.race) {
      requestData.breed = formik.values.race;
    }

    dispatch(LOADING_START());
    dispatch(provinceNeedRequestFormService(requestData)).then((r) => {
      dispatch(LOADING_END());
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: r.error ? "مشکلی پیش آمده است!" : "عملیات با موفقیت انجام شد.",
        severity: r.error ? "error" : "success",
      });
      if (!r.error) {
        dispatch(
          getSlaughtersKillRequestService({
            selectedDate1,
            selectedDate2,
          })
        );
        dispatch(
          DRAWER({
            right: false,
            bottom: false,
            top: false,
            content: null,
          })
        );
      }
    });
  };
  return (
    <Grid container spacing={2} padding={2}>
      <Typography variant="h6" fontWeight="bold">
        توضیحات
      </Typography>
      <Typography variant="body2" textAlign="justify">
        لطفاً نیاز اولیه کشتار را بررسی کرده و در صورت تأیید یا رد، اقدام لازم
        را انجام دهید.{" "}
      </Typography>
      <Typography
        textAlign="justify"
        variant="body2"
        marginBottom={2}
        color="error"
        mt={2}
      >
        شما می‌توانید حجم و نژاد مرغ درخواستی را به‌دلخواه ویرایش کنید.{" "}
      </Typography>
      <Typography variant="h6" fontWeight="bold" marginTop={2}>
        درخواست کشتارگاه:
      </Typography>
      <Grid container spacing={1}>
        <Grid item xs={12}>
          <Typography>
            تعداد درخواستی: {quantity.toLocaleString()} قطعه
          </Typography>
        </Grid>
        <Grid item xs={12}>
          <Typography>نژاد: {item?.chickenBreed}</Typography>
        </Grid>
      </Grid>

      <AnimatePresence>
        {isDenied ? (
          <motion.div
            key="denied-form"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.3 }}
          >
            <Grid container spacing={2} marginTop={2}>
              <Grid item xs={12}>
                <TextField
                  multiline
                  rows={4}
                  fullWidth
                  id="rejectText"
                  label="پیام خود را وارد کنید"
                  variant="outlined"
                  value={formik.values.rejectText}
                  error={
                    formik.touched.rejectText &&
                    Boolean(formik.errors.rejectText)
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.rejectText && formik.errors.rejectText
                  }
                />
              </Grid>
              <Grid item xs={6}>
                <Button
                  variant="outlined"
                  color="secondary"
                  fullWidth
                  onClick={() => setIsDenied(false)}
                >
                  لغو
                </Button>
              </Grid>
              <Grid item xs={6}>
                <Button
                  variant="contained"
                  color="error"
                  fullWidth
                  onClick={() => {
                    dispatch(LOADING_START());
                    dispatch(
                      provinceNeedRequestFormService({
                        kill_request_key: killRequestKey,
                        state: "rejected",
                        msg: formik.values.rejectText,
                      })
                    ).then((r) => {
                      dispatch(LOADING_END());
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.error
                          ? "مشکلی پیش آمده است!"
                          : "عملیات با موفقیت انجام شد.",
                        severity: r.error ? "error" : "success",
                      });
                      if (!r.error) {
                        dispatch(
                          getSlaughtersKillRequestService({
                            selectedDate1,
                            selectedDate2,
                          })
                        );
                        dispatch(
                          DRAWER({
                            right: false,
                            bottom: false,
                            top: false,
                            content: null,
                          })
                        );
                        setIsDenied(false);
                      }
                    });
                  }}
                >
                  رد اطلاعات و پیام به استان
                </Button>
              </Grid>
            </Grid>
          </motion.div>
        ) : (
          <motion.div
            key="accept-form"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.3 }}
          >
            <Grid container spacing={2} marginTop={2}>
              <Grid item xs={12}>
                <NumberInput
                  allowLeadingZeros
                  thousandSeparator=","
                  name="number"
                  id="number"
                  label="تعداد"
                  value={formik.values.number}
                  onChange={formik.handleChange}
                  error={formik.touched.number && Boolean(formik.errors.number)}
                  helperText={formik.touched.number && formik.errors.number}
                  fullWidth
                  inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
                />
              </Grid>
              <Grid item xs={12}>
                <FormControl fullWidth>
                  <InputLabel id="race-label">نژاد مرغ</InputLabel>
                  <Select
                    labelId="race-label"
                    id="race"
                    value={formik.values.race}
                    onChange={(e) =>
                      formik.setFieldValue("race", e.target.value)
                    }
                    onBlur={formik.handleBlur}
                    error={formik.touched.race && Boolean(formik.errors.race)}
                  >
                    <MenuItem value="آرین">آرین</MenuItem>
                    <MenuItem value="راس">راس</MenuItem>
                    <MenuItem value="آربراکرز (آپلاس)">
                      آربراکرز (آپلاس)
                    </MenuItem>
                    <MenuItem value="کاب">کاب</MenuItem>
                    <MenuItem value="هوبارد">هوبارد</MenuItem>
                    <MenuItem value="ترکیبی">ترکیبی</MenuItem>
                    <MenuItem value="وارداتی">وارداتی</MenuItem>
                  </Select>
                  <FormHelperText>
                    {formik.touched.race && formik.errors.race}
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={6}>
                <Button
                  variant="contained"
                  color="success"
                  fullWidth
                  onClick={handleAccept}
                >
                  {acceptButtonText}
                </Button>
              </Grid>
              <Grid item xs={6}>
                <Button
                  variant="contained"
                  color="error"
                  fullWidth
                  onClick={() => setIsDenied(true)}
                >
                  {rejectButtonText}
                </Button>
              </Grid>
            </Grid>
          </motion.div>
        )}
      </AnimatePresence>
    </Grid>
  );
}
