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

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

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

  const initialValues = {
    quarantineCode: item?.clearanceCode || "",
    carcassCount: item?.numberOfCarcasses || "",
    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
            ? slaughterEditOutOfProvinceService({
                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(fetchSlaughterBroadcastAndProducts());
              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>
  );
};
