import { useDispatch } from "react-redux";
import { useContext } from "react";
import moment from "moment";
import { Field, Form, Formik } from "formik";
import { DatePicker } from "@mui/x-date-pickers";
import { Button, TextField } from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { AppContext } from "../../../../contexts/AppContext";
import { Grid } from "../../../../components/grid/Grid";
import { guildEditOutOfProvinceService } from "../../../slaughter-house/services/slaughterEditOutOfProvinceService";
import {
  guildSubmitOutOfProvinceService,
  slaughterSubmitOutOfProvinceService,
} from "../../../slaughter-house/services/slaughter-submit-out-province-service";
import { stewardEditBuyerDataService } from "../../../guild/services/steward-edit-sell-out-buyer";
import { guildGetInventoryStockService } from "../../../guild/services/guild-get-inventory-stock";
import { guildGetFreeSaleBarService } from "../../../guild/services/guild-get-free-sale-bar";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { fetchStewardBroadcastAndProducts } from "../../services/handle-fetch-steward-products";

const validationSchema = Yup.object().shape({
  quarantineCode: Yup.string().required("کد قرنطینه الزامی است"),
  carcassCount: Yup.number().required("حجم لاشه الزامی است"),
  carcassWeight: Yup.number().required("وزن لاشه الزامی است"),
  date: Yup.string().required("تاریخ الزامی است"),
});

export const StewardSellOutOfProvinceEditSell = ({
  fetchItems,
  isEdit,
  item,
  selectedDate,
  stewardKey,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const initialValues = {
    quarantineCode: item?.clearanceCode || "",
    carcassCount: item?.numberOfCarcasses || "0",
    carcassWeight: item?.weightOfCarcasses || "",
    date: item?.date || moment().format("YYYY-MM-DD HH:mm:ss"),
  };

  return (
    <Grid>
      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={(values) => {
          const payload = {
            ...values,
            date: values.date,
            number_of_carcasses: values.carcassCount,
            weight_of_carcasses: values.carcassWeight,
          };

          if (values.quarantineCode !== item?.quarantineCode) {
            payload.quarantineCode = values.quarantineCode;
          }

          const service = stewardKey
            ? isEdit
              ? guildEditOutOfProvinceService({ key: item?.key, ...payload })
              : guildSubmitOutOfProvinceService({
                  steward_key: stewardKey,
                  ...payload,
                })
            : isEdit
            ? stewardEditBuyerDataService({
                key: item?.key,
                driver_mobile: values.driverPhone,
                ...payload,
              })
            : slaughterSubmitOutOfProvinceService({
                driver_mobile: values.driverPhone,
                ...payload,
              });

          dispatch(service).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              stewardKey
                ? dispatch(guildGetInventoryStockService({ date: values.date }))
                : fetchItems();

              stewardKey &&
                dispatch(
                  guildGetFreeSaleBarService({
                    date: values.date,
                    steward_key: stewardKey,
                  })
                );

              dispatch(fetchStewardBroadcastAndProducts());
              dispatch(DRAWER({ right: false, bottom: false, content: null }));
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      >
        {({ errors, touched, setFieldValue, values }) => (
          <Form>
            <Grid
              container
              spacing={1}
              justifyContent="center"
              alignItems="center"
            >
              <Grid item xs={12}>
                <Field
                  as={TextField}
                  name="quarantineCode"
                  label="کد قرنطینه"
                  fullWidth
                  error={
                    touched.quarantineCode && Boolean(errors.quarantineCode)
                  }
                  helperText={touched.quarantineCode && errors.quarantineCode}
                />
              </Grid>
              <Grid item xs={12}>
                <Field
                  as={TextField}
                  name="carcassCount"
                  label="حجم لاشه"
                  type="number"
                  fullWidth
                  error={touched.carcassCount && Boolean(errors.carcassCount)}
                  helperText={touched.carcassCount && errors.carcassCount}
                />
              </Grid>
              <Grid item xs={12}>
                <DatePicker
                  label="تاریخ"
                  value={moment(values.date)}
                  onChange={(val) => {
                    const formatted = moment(val).format("YYYY-MM-DD HH:mm:ss");
                    setFieldValue("date", formatted);
                  }}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      fullWidth
                      error={touched.date && Boolean(errors.date)}
                      helperText={touched.date && errors.date}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Field
                  as={TextField}
                  name="carcassWeight"
                  label="وزن لاشه"
                  type="number"
                  fullWidth
                  error={touched.carcassWeight && Boolean(errors.carcassWeight)}
                  helperText={touched.carcassWeight && errors.carcassWeight}
                />
              </Grid>
              <Grid item xs={12}>
                <Button variant="contained" fullWidth type="submit">
                  {isEdit ? "ویرایش" : "ثبت"}
                </Button>
              </Grid>
            </Grid>
          </Form>
        )}
      </Formik>
    </Grid>
  );
};
