import { Button, InputAdornment, TextField, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { useFormik } from "formik";
// import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Yup } from "../../../lib/yup/yup";
import { AppContext } from "../../../contexts/AppContext";
import { fixBase64 } from "../../../utils/toBase64";
import { Grid } from "../../../components/grid/Grid";
import { SPACING } from "../../../data/spacing";
import { ImageUpload } from "../../../components/image-upload/ImageUpload";
import { guildSubmitFreeBar } from "../services/guild-submit-free-bar";
import { guildGetInventoryStockService } from "../services/guild-get-inventory-stock";
import { guildGetInventoryAllocatedService } from "../services/guild-get-inventory-allocated";
import { DRAWER } from "../../../lib/redux/slices/appSlice";
import { guildGetFreeBars } from "../services/guild-get-free-bars";
import { guildEditFreeBar } from "../services/guild-edit-free-bar";

const ValidationSchema = Yup.object().shape({
  // kill_house_key: Yup.string().required("کد خانه کشتار الزامی است"),
  slaughter_name: Yup.string().required("نام کشتارگاه الزامی است"),
  slaughter_mobile: Yup.string()
    .required("شماره موبایل کشتارگاه الزامی است")
    .min(11, "شماره موبایل باید دقیقاً 11 رقم باشد")
    .max(11, "شماره موبایل باید دقیقاً 11 رقم باشد"),
  province: Yup.string().required("استان الزامی است"),
  city: Yup.string().required("شهر الزامی است"),
  vet_farm_name: Yup.string().required("نام دامپزشک مربوطه الزامی است"),
  vet_farm_mobile: Yup.string()
    .required("شماره موبایل دامپزشک مربوطه الزامی است")
    .min(11, "شماره موبایل باید دقیقاً 11 رقم باشد")
    .max(11, "شماره موبایل باید دقیقاً 11 رقم باشد"),
  driver_name: Yup.string().required("نام راننده الزامی است"),
  driver_mobile: Yup.string()
    .required("شماره موبایل راننده الزامی است")
    .min(11, "شماره موبایل باید دقیقاً 11 رقم باشد")
    .max(11, "شماره موبایل باید دقیقاً 11 رقم باشد"),
  car: Yup.string().required("نوع خودرو الزامی است"),
  number_of_carcasses: Yup.number()
    .required("حجم لاشه الزامی است")
    .min(1, "حجم لاشه باید بیشتر از 0 باشد"),
  weight_of_carcasses: Yup.number()
    .required("وزن لاشه الزامی است")
    .min(0.01, "وزن باید بیشتر از 0 باشد"),
  bar_image: Yup.string(),
  selectedDate: Yup.date().required("تاریخ الزامی است"),
});

export const GuildSubmitFreeBar = ({ guildKey, item, editMode }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  //   const { inventorySelectedKillHouse } = useSelector(
  //     (state) => state.slaughterSlice
  //   );
  const [, , selectedDate1] = useContext(AppContext);

  const thenCallback = (r) => {
    dispatch(
      guildGetInventoryStockService({
        date: selectedDate1,
      })
    );
    dispatch(
      guildGetInventoryAllocatedService({
        date: selectedDate1,
      })
    );

    dispatch(
      guildGetFreeBars({
        date: selectedDate1,
      })
    );

    if (r.error) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: r.error,
        severity: "error",
      });
    } else {
      dispatch(DRAWER({ right: false, bottom: false, content: null }));
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "عملیات با موفقیت انجام شد.",
        severity: "success",
      });
    }
  };

  const [profileImages, setProfileImages] = useState([]);

  const formik = useFormik({
    initialValues: {
      kill_house_key: "",
      slaughter_name: item ? item.killHouseName : "",
      slaughter_mobile: item ? item.killHouseMobile : "",
      province: item ? item.province : "",
      city: item ? item.city : "",
      vet_farm_name: item ? item.killHouseVetName : "",
      vet_farm_mobile: item ? item.killHouseVetMobile : "",
      driver_name: item ? item.driverName : "",
      driver_mobile: item ? item.driverMobile : "",
      car: item ? item.car : "",
      number_of_carcasses: item ? item.numberOfCarcasses : "",
      weight_of_carcasses: item ? item.weightOfCarcasses : "",
      bar_image: "",
      selectedDate: item ? new Date(item.date) : new Date(),
    },
    validationSchema: ValidationSchema,
  });

  useEffect(() => {
    formik.validateForm();
    if (item?.barImage) {
      factorPaymentHandler([{ data_url: item?.barImage }]);
    }
  }, []);

  const factorPaymentHandler = (imageList, addUpdateIndex) => {
    if (imageList[0]) {
      formik.setFieldValue("bar_image", fixBase64(imageList[0]?.data_url));
    }
    setProfileImages(imageList);
  };

  return (
    <Grid container direction="column">
      <form
        style={{
          display: "flex",
          flexDirection: "column",
          gap: SPACING.LARGE,
        }}
      >
        <DatePicker
          disabled={editMode}
          label="تاریخ"
          id="date"
          renderInput={(params) => (
            <TextField style={{ width: "100%" }} {...params} />
          )}
          value={formik.values.selectedDate}
          onChange={(e) => {
            formik.setFieldValue("selectedDate", new Date(e));
          }}
        />
        <TextField
          id="slaughter_name"
          name="slaughter_name"
          label="نام کشتارگاه"
          value={formik.values.slaughter_name}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.slaughter_name &&
            Boolean(formik.errors.slaughter_name)
          }
          helperText={
            formik.touched.slaughter_name && formik.errors.slaughter_name
          }
        />

        <TextField
          id="slaughter_mobile"
          name="slaughter_mobile"
          label="تلفن کشتارگاه"
          value={formik.values.slaughter_mobile}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.slaughter_mobile &&
            Boolean(formik.errors.slaughter_mobile)
          }
          helperText={
            formik.touched.slaughter_mobile && formik.errors.slaughter_mobile
          }
        />

        <TextField
          id="province"
          name="province"
          label="استان"
          value={formik.values.province}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.province && Boolean(formik.errors.province)}
          helperText={formik.touched.province && formik.errors.province}
        />

        <TextField
          id="city"
          name="city"
          label="شهر"
          value={formik.values.city}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.city && Boolean(formik.errors.city)}
          helperText={formik.touched.city && formik.errors.city}
        />
        <TextField
          id="vet_farm_name"
          name="vet_farm_name"
          label="نام دامپزشک کشتارگاه"
          value={formik.values.vet_farm_name}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.vet_farm_name && Boolean(formik.errors.vet_farm_name)
          }
          helperText={
            formik.touched.vet_farm_name && formik.errors.vet_farm_name
          }
        />

        <TextField
          id="vet_farm_mobile"
          name="vet_farm_mobile"
          label="تلفن دامپزشک کشتارگاه"
          value={formik.values.vet_farm_mobile}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.vet_farm_mobile &&
            Boolean(formik.errors.vet_farm_mobile)
          }
          helperText={
            formik.touched.vet_farm_mobile && formik.errors.vet_farm_mobile
          }
        />

        <TextField
          id="driver_name"
          name="driver_name"
          label="نام راننده"
          value={formik.values.driver_name}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.driver_name && Boolean(formik.errors.driver_name)
          }
          helperText={formik.touched.driver_name && formik.errors.driver_name}
        />

        <TextField
          id="driver_mobile"
          name="driver_mobile"
          label="تلفن راننده"
          value={formik.values.driver_mobile}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.driver_mobile && Boolean(formik.errors.driver_mobile)
          }
          helperText={
            formik.touched.driver_mobile && formik.errors.driver_mobile
          }
        />

        <TextField
          id="car"
          name="car"
          label="خودرو"
          value={formik.values.car}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.car && Boolean(formik.errors.car)}
          helperText={formik.touched.car && formik.errors.car}
        />

        <TextField
          id="number_of_carcasses"
          name="number_of_carcasses"
          label="حجم لاشه"
          InputProps={{
            endAdornment: <InputAdornment position="end">قطعه</InputAdornment>,
          }}
          value={formik.values.number_of_carcasses}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.number_of_carcasses &&
            Boolean(formik.errors.number_of_carcasses)
          }
          helperText={
            formik.touched.number_of_carcasses &&
            formik.errors.number_of_carcasses
          }
        />

        <TextField
          id="weight_of_carcasses"
          name="weight_of_carcasses"
          label="وزن لاشه"
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">کیلوگرم</InputAdornment>
            ),
          }}
          value={formik.values.weight_of_carcasses}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.weight_of_carcasses &&
            Boolean(formik.errors.weight_of_carcasses)
          }
          helperText={
            formik.touched.weight_of_carcasses &&
            formik.errors.weight_of_carcasses
          }
        />

        <ImageUpload
          onChange={factorPaymentHandler}
          images={profileImages}
          maxNumber={1}
          title={"تصویر بار"}
        />

        {formik.touched.driver_mobile &&
          Boolean(formik.errors.driver_mobile) && (
            <Typography color="error">ثبت تصویر بار الزامی است</Typography>
          )}

        <Button
          disabled={!formik.isValid}
          onClick={() => {
            if (editMode) {
              dispatch(
                guildEditFreeBar({
                  key: guildKey,
                  kill_house_name: formik.values.slaughter_name,
                  kill_house_mobile: formik.values.slaughter_mobile,
                  kill_house_vet_name: formik.values.vet_farm_name,
                  kill_house_vet_mobile: formik.values.vet_farm_mobile,
                  province: formik.values.province,
                  city: formik.values.city,
                  driver_name: formik.values.driver_name,
                  driver_mobile: formik.values.driver_mobile,
                  car: formik.values.car,
                  number_of_carcasses: formik.values.number_of_carcasses,
                  weight_of_carcasses: formik.values.weight_of_carcasses,
                  bar_image: formik.values.bar_image,
                  date: formik.values.selectedDate,
                })
              ).then(thenCallback);
            } else {
              dispatch(
                guildSubmitFreeBar({
                  steward_key: guildKey,
                  kill_house_name: formik.values.slaughter_name,
                  kill_house_mobile: formik.values.slaughter_mobile,
                  kill_house_vet_name: formik.values.vet_farm_name,
                  kill_house_vet_mobile: formik.values.vet_farm_mobile,
                  province: formik.values.province,
                  city: formik.values.city,
                  driver_name: formik.values.driver_name,
                  driver_mobile: formik.values.driver_mobile,
                  car: formik.values.car,
                  number_of_carcasses: formik.values.number_of_carcasses,
                  weight_of_carcasses: formik.values.weight_of_carcasses,
                  bar_image: formik.values.bar_image,
                  date: formik.values.selectedDate,
                })
              ).then(thenCallback);
            }
          }}
          fullWidth
          variant="contained"
          color="primary"
        >
          {editMode ? "ویرایش" : "ثبت"}
        </Button>
      </form>
    </Grid>
  );
};
