import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import moment from "moment";
import {
  Button,
  Divider,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { provinceChainsSubmitAllocation } from "../../services/province-chains-submut-allocation";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import Radio from "@mui/material/Radio";
import RadioGroup from "@mui/material/RadioGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormControl from "@mui/material/FormControl";
import FormLabel from "@mui/material/FormLabel";
import { CarPelak } from "../../../../components/car-pelak/CarPelak";
import { SPACING } from "../../../../data/spacing";
import { provinceGetKillHousesForAllocation } from "../../services/province-get-killhouses-for-allocation";
import { provinceChainsEditAllocation } from "../../services/province-chains-edit-allocation";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const ChainsAllocation = ({ item, updateTable, isEdit }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [value, setValue] = React.useState(
    isEdit ? (item?.outProvince ? "out" : "native") : "out"
  );
  const [selectedKillhouse, setSelectedKillHouse] = React.useState();

  useEffect(() => {
    if (value === "native") {
      dispatch(LOADING_START());
      dispatch(provinceGetKillHousesForAllocation()).then((r) => {
        dispatch(LOADING_END());
        const d = r?.payload.data.map((item) => {
          return { name: item.name, key: item.key };
        });
        setKillhouses(d);
        setSelectedKillHouse("");
      });
    }
  }, [value]);

  const [killhouses, setKillhouses] = useState([]);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const [driverPelak, setDriverPelak] = useState([]);

  const carPelakHandleChange = (pelak1, pelak2, pelak3, pelak4) => {
    setDriverPelak([pelak1, pelak2, pelak3, pelak4]);
  };

  const formik = useFormik({
    initialValues: {
      weight: isEdit ? item?.indexWeight : "",
      quantity: isEdit ? item?.quantity : "",
      driverName: isEdit ? item?.driverName : "",
      driverMobile: isEdit ? item?.driverMobile : "",
      driverCar: isEdit ? item?.typeCar : "",
      healthCode: isEdit ? item?.healthCode : "",
    },
    validationSchema: Yup.object({
      weight: Yup.number().required("این فیلد اجباری است!"),
      quantity: Yup.number().required("این فیلد اجباری است!"),
      driverName: Yup.string().required("این فیلد اجباری است!"),
      healthCode: Yup.string().required("این فیلد اجباری است!"),
      driverMobile: Yup.string()
        .required("شماره موبایل کشتارگاه الزامی است")
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
      driverCar: Yup.string().required("این فیلد اجباری است!"),
      // driverhealthCode: Yup.string().required("این فیلد اجباری است!"),
    }),
  });

  const [, , selectedDate1, setSelectedDate1, ,] = useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
  }, []);

  const formikbuyer = useFormik({
    initialValues: {
      name: isEdit ? item?.buyerName : "",
      mobile: isEdit ? item?.buyerMobile : "",
      province: isEdit ? item?.province : "",
      city: isEdit ? item?.city : "",
    },
    validationSchema: Yup.object({
      name: Yup.string().required("نام اجباری است"),
      mobile: Yup.string()
        .required("شماره موبایل کشتارگاه الزامی است")
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
      province: Yup.string().required("استان اجباری است"),
      city: Yup.string().required("شهرستان اجباری است"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
    formikbuyer.validateForm();
  }, []);

  const isFormValid = () => {
    if (value === "native") {
      return formik.isValid && selectedKillhouse && driverPelak[1];
    } else {
      return formik.isValid && formikbuyer.isValid && driverPelak[1];
    }
  };

  useEffect(() => {
    let newVal = formik.values.weight;
    const mystring = formik.values.weight.toString().split(".").join("");
    if (formik.values.weight) {
      if (mystring.length <= 3) {
        if (mystring.length === 2) {
          newVal = mystring[0] + "." + mystring[1];
        }
        if (mystring.length === 3) {
          newVal = mystring[0] + "." + mystring[1] + mystring[2];
        }
      }
    }
    if (isNaN(Number.parseFloat(newVal))) {
      formik.setFieldValue("weight", "");
    } else {
      formik.setFieldValue("weight", Number.parseFloat(newVal));
    }
  }, [formik.values.weight]);

  return (
    <Grid container xs={12} alignItems="center" justifyContent="center" gap={2}>
      {!isEdit && (
        <>
          <Grid container xs={12}>
            <Typography variant="body2">شرکت زنجیره:{"‌‌ ‌"}</Typography>
            <Typography variant="body2" style={{ color: "gray" }}>
              {item?.companyName}
            </Typography>
          </Grid>
          <Grid container xs={12}>
            <Typography variant="body2">مرغدار:{"‌‌ ‌"}</Typography>
            <Typography variant="body2" style={{ color: "gray" }}>
              {item.poultry.userprofile.fullName} (
              {item.poultry.userprofile.mobile})
            </Typography>
          </Grid>
          <Grid container xs={12}>
            <Typography variant="body2">نژاد:{"‌‌ ‌"}</Typography>
            <Typography variant="body2" style={{ color: "gray" }}>
              {item.chickenBreed}
            </Typography>
          </Grid>
          <Grid container xs={12}>
            <Typography variant="body2">سن جوجه:{"‌‌ ‌"}</Typography>
            <Typography variant="body2" style={{ color: "gray" }}>
              {item.age}
            </Typography>
          </Grid>
        </>
      )}
      {isEdit && (
        <>
          <Grid container xs={12}>
            <Typography variant="body2">مرغدار:{"‌‌ ‌"}</Typography>
            <Typography variant="body2" style={{ color: "gray" }}>
              {item?.poultryHatching?.poultry?.unitName} (
              {item?.poultryHatching?.poultry?.user?.mobile})
            </Typography>
          </Grid>
          <Grid container xs={12}>
            <Typography variant="body2">شرکت زنجیره:{"‌‌ ‌"}</Typography>
            <Typography variant="body2" style={{ color: "gray" }}>
              {item?.chainCompany?.name}
            </Typography>
          </Grid>
        </>
      )}
      <Divider style={{ width: "100%" }} />

      <Grid xs={12}>
        <DatePicker
          label=" تاریخ"
          id="date"
          renderInput={(params) => <TextField {...params} />}
          value={selectedDate1}
          onChange={(e) => {
            setSelectedDate1(moment(e).format("YYYY-MM-DD"));
          }}
        />
      </Grid>
      <Grid xs={12}>
        <TextField
          id="quantity"
          fullWidth
          label="حجم (قطعه)"
          variant="outlined"
          sx={{ width: "100%" }}
          value={formik.values.quantity}
          error={
            formik.touched.quantity ? Boolean(formik.errors.quantity) : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.quantity && Boolean(formik.errors.quantity)
              ? formik.errors.quantity
              : null
          }
        />
      </Grid>
      <Grid xs={12}>
        <TextField
          id="weight"
          fullWidth
          label="میانگین وزن"
          variant="outlined"
          sx={{ width: "100%" }}
          value={formik.values.weight}
          error={formik.touched.weight ? Boolean(formik.errors.weight) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.weight && Boolean(formik.errors.weight)
              ? formik.errors.weight
              : null
          }
        />
      </Grid>
      {formik.values.weight && formik.values.quantity && (
        <Grid
          container
          style={{
            borderStyle: "solid",
            borderWidth: "2px",
            borderColor: "gray",
            borderRadius: "6px",
          }}
          xs={12}
          p={1}
        >
          <Typography variant="body2" color="primary">
            وزن کل: {"‌‌ ‌"}
          </Typography>
          <Typography variant="body2">
            {parseInt(formik.values.quantity * formik.values.weight)} کیلوگرم
          </Typography>
        </Grid>
      )}

      <FormControl>
        <FormLabel id="demo-controlled-radio-buttons-group">نوع فروش</FormLabel>
        <RadioGroup
          row
          aria-labelledby="demo-controlled-radio-buttons-group"
          name="controlled-radio-buttons-group"
          value={value}
          onChange={handleChange}
        >
          <FormControlLabel
            value="out"
            control={<Radio disabled={isEdit} />}
            label="خارج استان"
          />
          <FormControlLabel
            value="native"
            control={<Radio disabled={isEdit} />}
            label="درون استان"
          />
        </RadioGroup>
      </FormControl>

      {value === "out" ? (
        <Grid
          container
          xs={12}
          alignItems="center"
          justifyContent="center"
          gap={SPACING.SMALL}
        >
          <Typography variant="body1">اطلاعات خریدار</Typography>
          <TextField
            label="نام و نام خانوادگی"
            name="name"
            value={formikbuyer.values.name}
            onChange={formikbuyer.handleChange}
            onBlur={formik.handleBlur}
            error={formikbuyer.touched.name && Boolean(formikbuyer.errors.name)}
            helperText={formikbuyer.touched.name && formikbuyer.errors.name}
            required
            fullWidth
          />
          <TextField
            fullWidth
            id="mobile"
            value={formikbuyer.values.mobile}
            error={
              formikbuyer.touched.mobile
                ? Boolean(formikbuyer.errors.mobile)
                : null
            }
            onChange={formikbuyer.handleChange}
            onBlur={formikbuyer.handleBlur}
            helperText={
              formikbuyer.touched.mobile && Boolean(formikbuyer.errors.mobile)
                ? formikbuyer.errors.mobile
                : null
            }
            label="موبایل"
            autoComplete="current-password"
            variant="outlined"
          />
          <TextField
            label="استان"
            name="province"
            value={formikbuyer.values.province}
            onChange={formikbuyer.handleChange}
            onBlur={formik.handleBlur}
            error={
              formikbuyer.touched.province &&
              Boolean(formikbuyer.errors.province)
            }
            helperText={
              formikbuyer.touched.province && formikbuyer.errors.province
            }
            required
            fullWidth
          />
          <TextField
            label="شهرستان"
            name="city"
            value={formikbuyer.values.city}
            onBlur={formik.handleBlur}
            onChange={formikbuyer.handleChange}
            error={formikbuyer.touched.city && Boolean(formikbuyer.errors.city)}
            helperText={formikbuyer.touched.city && formikbuyer.errors.city}
            required
            fullWidth
          />
        </Grid>
      ) : (
        <Grid xs={12}>
          <FormControl
            fullWidth
            error={
              formik.errors.selectedOption && formik.touched.selectedOption
            }
          >
            <InputLabel>کشتارگاه را انتخاب کنید</InputLabel>
            <Select
              fullWidth
              label="کشتارگاه را انتخاب کنید"
              id="selectedKillhouse"
              name="selectedKillhouse"
              onChange={(e) => {
                const [key] = e.target.value.split("#");
                setSelectedKillHouse(key);
              }}
              onBlur={formik.handleBlur}
            >
              {killhouses?.map((option) => (
                <MenuItem
                  key={option}
                  value={`${option.key + "#" + option.killer}`}
                >
                  {`کشتارگاه ${option.name}`}
                </MenuItem>
              ))}
            </Select>
            {formik.errors.selectedKillhouse &&
              formik.touched.selectedKillhouse && (
                <div>{formik.errors.selectedKillhouse}</div>
              )}
          </FormControl>
        </Grid>
      )}
      <Grid
        container
        xs={12}
        alignItems="center"
        justifyContent="center"
        gap={SPACING.SMALL}
      >
        <Typography variant="body1">اطلاعات خودرو حمل</Typography>
        <TextField
          label="نام و نام خانوادگی راننده"
          name="driverName"
          value={formik.values.driverName}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.driverName && Boolean(formik.errors.driverName)}
          helperText={
            formik.touched.driverName && Boolean(formik.errors.driverName)
              ? formik.errors.driverName
              : null
          }
          required
          fullWidth
        />
        <TextField
          fullWidth
          id="driverMobile"
          value={formik.values.driverMobile}
          error={
            formik.touched.driverMobile
              ? Boolean(formik.errors.driverMobile)
              : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.driverMobile && Boolean(formik.errors.driverMobile)
              ? formik.errors.driverMobile
              : null
          }
          label="موبایل راننده"
          autoComplete="current-password"
          variant="outlined"
        />
        <TextField
          label="کد بهداشتی "
          name="healthCode"
          value={formik.values.healthCode}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.healthCode && Boolean(formik.errors.healthCode)}
          helperText={formik.touched.healthCode && formik.errors.healthCode}
          type="tel"
          required
          fullWidth
        />

        <TextField
          label="مدل خودرو"
          name="driverCar"
          value={formik.values.driverCar}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.driverCar && Boolean(formik.errors.driverCar)}
          helperText={formik.touched.driverCar && formik.errors.driverCar}
          type="tel"
          required
          fullWidth
        />
        <CarPelak
          width="100%"
          handleChange={carPelakHandleChange}
          pelakInitial={isEdit ? item?.pelak : ""}
        />
        {/* <TextField
          label="کد بهداشتی حمل"
          name="driverhealthCode"
          value={formik.values.driverhealthCode}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.driverhealthCode &&
            Boolean(formik.errors.driverhealthCode)
          }
          helperText={
            formik.touched.driverhealthCode && formik.errors.driverhealthCode
          }
          required
          fullWidth
        /> */}
      </Grid>
      <Button
        disabled={!isFormValid()}
        variant="contained"
        fullWidth
        onClick={() => {
          if (
            getRoleFromUrl() !== "SuperAdmin" &&
            getRoleFromUrl() !== "AdminX" &&
            ((item.age > 40 && formik.values.weight < 1.9) ||
              (item.age > 40 && formik.values.weight > 4) ||
              (item.age < 40 && formik.values.weight < 1.5) ||
              (item.age < 40 && formik.values.weight > 4) ||
              (item.age > 56 && formik.values.weight < 2.8) ||
              (item.age > 56 && formik.values.weight > 4))
          ) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg:
                item?.age > 56
                  ? "میانگین وزنی باید عددی بین 2.8 تا 4 کیلوگرم باشد!"
                  : item?.age > 40
                  ? "میانگین وزنی باید عددی بین 1.9 تا 4 کیلوگرم باشد!"
                  : "میانگین وزنی باید عددی بین 1.5 تا 4 باشد!",
              severity: "error",
            });
          } else {
            if (isEdit) {
              if (value === "native") {
                dispatch(
                  provinceChainsEditAllocation({
                    chain_allcation_key: item?.key,
                    quantity: formik.values.quantity,
                    weight: parseInt(
                      formik.values.quantity * formik.values.weight
                    ),
                    index_weight: formik.values.weight,
                    date: selectedDate1,
                    out_province: false,
                    driver_name: formik.values.driverName,
                    driver_mobile: formik.values.driverMobile,
                    health_code: formik.values.healthCode,
                    type_car: formik.values.driverCar,
                    pelak:
                      driverPelak[0] +
                      " " +
                      driverPelak[1] +
                      " " +
                      driverPelak[2] +
                      " " +
                      driverPelak[3],
                    kill_house_key: selectedKillhouse,
                  })
                ).then((r) => {
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    updateTable(1);
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "بار با موفقیت ثبت شد؛ جهت مشاهده به بخش مدیریت بارها در همین صفحه مراجعه کنید",
                      severity: "success",
                    });
                  }
                });
              } else {
                dispatch(
                  provinceChainsEditAllocation({
                    chain_allcation_key: item?.key,
                    quantity: formik.values.quantity,
                    weight: parseInt(
                      formik.values.quantity * formik.values.weight
                    ),
                    index_weight: formik.values.weight,
                    date: selectedDate1,
                    out_province: true,
                    driver_name: formik.values.driverName,
                    driver_mobile: formik.values.driverMobile,
                    health_code: formik.values.healthCode,
                    type_car: formik.values.driverCar,
                    pelak:
                      driverPelak[0] +
                      " " +
                      driverPelak[1] +
                      " " +
                      driverPelak[2] +
                      " " +
                      driverPelak[3],
                    buyer_name: formikbuyer.values.name,
                    buyer_mobile: formikbuyer.values.mobile,
                    city: formikbuyer.values.city,
                    province: formikbuyer.values.name,
                  })
                ).then((r) => {
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );

                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    updateTable(1);
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "بار با موفقیت ثبت شد؛ جهت مشاهده به بخش مدیریت بارها در همین صفحه مراجعه کنید",
                      severity: "success",
                    });
                  }
                });
              }
            } else {
              if (value === "native") {
                dispatch(
                  provinceChainsSubmitAllocation({
                    hatching_key: item?.key,
                    quantity: formik.values.quantity,
                    weight: parseInt(
                      formik.values.quantity * formik.values.weight
                    ),
                    index_weight: formik.values.weight,
                    date: selectedDate1,
                    out_province: false,
                    driver_name: formik.values.driverName,
                    driver_mobile: formik.values.driverMobile,
                    health_code: formik.values.healthCode,
                    type_car: formik.values.driverCar,
                    pelak:
                      driverPelak[0] +
                      " " +
                      driverPelak[1] +
                      " " +
                      driverPelak[2] +
                      " " +
                      driverPelak[3],
                    kill_house_key: selectedKillhouse,
                  })
                ).then((r) => {
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );

                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "بار با موفقیت ثبت شد؛ جهت مشاهده به بخش مدیریت بارها در همین صفحه مراجعه کنید",
                      severity: "success",
                    });
                  }
                });
              } else {
                dispatch(
                  provinceChainsSubmitAllocation({
                    hatching_key: item?.key,
                    quantity: formik.values.quantity,
                    weight: parseInt(
                      formik.values.quantity * formik.values.weight
                    ),
                    index_weight: formik.values.weight,
                    date: selectedDate1,
                    out_province: true,
                    driver_name: formik.values.driverName,
                    driver_mobile: formik.values.driverMobile,
                    health_code: formik.values.healthCode,
                    type_car: formik.values.driverCar,
                    pelak:
                      driverPelak[0] +
                      " " +
                      driverPelak[1] +
                      " " +
                      driverPelak[2] +
                      " " +
                      driverPelak[3],
                    buyer_name: formikbuyer.values.name,
                    buyer_mobile: formikbuyer.values.mobile,
                    city: formikbuyer.values.city,
                    province: formikbuyer.values.name,
                  })
                ).then((r) => {
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );

                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "بار با موفقیت ثبت شد؛ جهت مشاهده به بخش مدیریت بارها در همین صفحه مراجعه کنید",
                      severity: "success",
                    });
                  }
                });
              }
            }
          }
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
