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, useSelector } 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({
  clearance_code: Yup.string().required("کد قرنطینه الزامی است"),
  number_of_carcasses: Yup.number().required("حجم لاشه الزامی است"),
  weight_of_carcasses: Yup.number().required("وزن لاشه الزامی است"),
  date: Yup.string().required("تاریخ الزامی است"),
});

export const SlaughterSubmitOutProvinceSell = ({
  fetchItems,
  isEdit,
  item,
  selectedDate,
  stewardKey,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const initialValues = {
    clearance_code: item?.clearanceCode || "",
    number_of_carcasses: item?.numberOfCarcasses || "",
    weight_of_carcasses: 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.number_of_carcasses,
            weight_of_carcasses: values.weight_of_carcasses,
          };

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

          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({
                  role_key: selectedSubUser?.key || "",
                })
              );
              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="clearance_code"
                  label="کد قرنطینه"
                  fullWidth
                  error={
                    touched.clearance_code && Boolean(errors.clearance_code)
                  }
                  helperText={touched.clearance_code && errors.clearance_code}
                />
              </Grid>
              <Grid item xs={12}>
                <Field
                  as={TextField}
                  name="number_of_carcasses"
                  label="حجم لاشه"
                  type="number"
                  fullWidth
                  error={
                    touched.number_of_carcasses &&
                    Boolean(errors.number_of_carcasses)
                  }
                  helperText={
                    touched.number_of_carcasses && errors.number_of_carcasses
                  }
                />
              </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="weight_of_carcasses"
                  label="وزن لاشه"
                  type="number"
                  fullWidth
                  error={
                    touched.weight_of_carcasses &&
                    Boolean(errors.weight_of_carcasses)
                  }
                  helperText={
                    touched.weight_of_carcasses && errors.weight_of_carcasses
                  }
                />
              </Grid>
              <Grid item xs={12}>
                <Button variant="contained" fullWidth type="submit">
                  {isEdit ? "ویرایش" : "ثبت"}
                </Button>
              </Grid>
            </Grid>
          </Form>
        )}
      </Formik>
    </Grid>
  );
};
