import React, { useContext, useEffect, useState } from "react";
import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import {
  Autocomplete,
  Button,
  Divider,
  FormControl,
  FormControlLabel,
  FormLabel,
  IconButton,
  InputAdornment,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import { CarPelak } from "../../../../components/car-pelak/CarPelak";
import { useDispatch } from "react-redux";
import { provinceFreeSaleEditRequestService } from "../../services/province-free-sale-edit-request";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceFreeSaleBuyers } from "../../services/province-free-sales-get-buyers";
import { avicultureGetWageType } from "../../../aviculture/services/aviculture-get-wage-type";
import AddIcon from "@mui/icons-material/Add";
import RemoveIcon from "@mui/icons-material/Remove";

export const ProvinceFreeSaleEditRequest = ({ item, fetchApiData }) => {
  const [openNotif] = useContext(AppContext);
  const [submitDriver, setSubmitDriver] = useState(
    item?.outProvinceDriverInfo?.driverName ? true : false
  );
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      noChicken: item?.quantity ? item?.quantity : "",
      weight: item?.IndexWeight ? item?.IndexWeight : "",
    },
    validationSchema: Yup.object({
      noChicken: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      weight: Yup.number()
        .test("weight", "وزن را تا دو رقم اعشار وارد کنید", (val, context) => {
          return (
            context.originalValue &&
            context.originalValue.toString().length <= 4
          );
        })
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
    }),
  });

  const formikDriver = useFormik({
    initialValues: {
      driverName: item?.outProvinceDriverInfo?.driverName
        ? item?.outProvinceDriverInfo?.driverName
        : "",
      driverMobile: item?.outProvinceDriverInfo?.driverMobile
        ? item?.outProvinceDriverInfo?.driverMobile
        : "",
      driverCar: item?.outProvinceDriverInfo?.driverCar
        ? item?.outProvinceDriverInfo?.driverCar
        : "",
      driverhealthCode: item?.outProvinceDriverInfo?.driverhealthCode
        ? item?.outProvinceDriverInfo?.driverhealthCode
        : "",
    },
    validationSchema: Yup.object({
      driverName: Yup.string().required("این فیلد اجباری است!"),
      driverMobile: Yup.string().required("این فیلد اجباری است!"),
      driverCar: Yup.string().required("این فیلد اجباری است!"),
      driverhealthCode: Yup.string().required("این فیلد اجباری است!"),
    }),
  });

  const formikPayer = useFormik({
    initialValues: {
      mobile: "",
      weight: "",
      quantity: "",
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required("شماره موبایل الزامی است")
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
      weight: Yup.number(),
      quantity: Yup.number(),
    }),
  });

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

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

  const [buyersData, setBuyersData] = useState([]);
  const [buyerSelected, setBuyerSelected] = useState();
  const [buyerItem, setBuyerItem] = useState();
  const [wageType, setWageType] = useState();

  useEffect(() => {
    setBuyerSelected(item?.outProvincePoultryRequestBuyer?.key);
    dispatch(avicultureGetWageType()).then((r) => {
      setWageType(r.payload.data.status);
    });

    dispatch(provinceFreeSaleBuyers()).then((r) => {
      setBuyersData(r.payload.data);
    });
  }, []);

  const [payerValue, setPayerValue] = useState("poultry");

  const handleChangePayer = (event) => {
    setPayerValue(event.target.value);
    if (event.target.value === "poultry") {
      formikPayer.setFieldValue("mobile", item.poultry.user.mobile);
    } else if (buyerItem) {
      formikPayer.setFieldValue("mobile", buyerItem.mobile);
    } else {
      formikPayer.setFieldValue(
        "mobile",
        item?.outProvincePoultryRequestBuyer.mobile
      );
    }
  };

  const wageValidation = () => {
    if (wageType) {
      return formikPayer.isValid;
    } else {
      return true;
    }
  };

  const isFormValid = () => {
    if (payerValue === "poultry") {
      if (submitDriver) {
        return (
          formik.isValid &&
          wageValidation() &&
          buyerSelected &&
          formikDriver &&
          driverPelak[0]
        );
      } else {
        return (
          formik.isValid &&
          formikPayer.isValid &&
          buyerSelected &&
          wageValidation()
        );
      }
    } else {
      if (submitDriver) {
        return (
          formik.isValid &&
          buyerSelected &&
          formikDriver &&
          driverPelak[0] &&
          wageValidation()
        );
      } else {
        return formik.isValid && buyerSelected && wageValidation();
      }
    }
  };

  useEffect(() => {
    formikPayer.setFieldValue("mobile", item.poultry.user.mobile);
  }, []);

  return (
    <Grid container gap={SPACING.SMALL} direction="column" display={"flex"}>
      <Grid container gap={SPACING.SMALL} direction={"column"}>
        <Grid
          xs={12}
          container
          justifyContent="space-between"
          alignItems="center"
        >
          <Typography variant="body2" style={{ color: "gray" }}>
            وزن کل:{" "}
          </Typography>
          <Typography variant="body2">
            {Math.floor(item.IndexWeight * item.quantity)?.toLocaleString()}
          </Typography>
        </Grid>{" "}
        <NumberInput
          allowLeadingZeros
          thousandSeparator=","
          fullWidth
          id="noChicken"
          label="تعداد مرغ برای کشتار"
          // InputProps={{
          //   inputComponent: NumberFormatCustom,
          // }}
          variant="outlined"
          value={formik.values.noChicken}
          error={
            formik.touched.noChicken ? Boolean(formik.errors.noChicken) : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.noChicken && Boolean(formik.errors.noChicken)
              ? formik.errors.noChicken
              : null
          }
        />
        <TextField
          id="weight"
          label="وزن تقریبی مرغ"
          variant="outlined"
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">کیلوگرم</InputAdornment>
            ),
          }}
          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
          xs={12}
          container
          justifyContent="space-between"
          alignItems="center"
        >
          <Typography variant="body2" style={{ color: "gray" }}>
            وزن کل:{" "}
          </Typography>
          <Typography variant="body2">
            {Math.floor(
              parseInt(formik.values.noChicken) *
                parseFloat(formik.values.weight)
            )?.toLocaleString()}
            {"‌ ‌"}
            کیلوگرم
          </Typography>
        </Grid>
        <Divider />
        <Typography variant="body1">اطلاعات خریدار</Typography>
        <Autocomplete
          disablePortal
          id="combo-box-demo"
          getOptionDisabled={(option) => option.disabled}
          options={
            buyersData
              ? buyersData?.map((i) => ({
                  id: i.key,
                  label: `${i?.fullname} / ${i.mobile} / استان ${i?.province}/ ${i?.city}`,
                  item: i,
                  mobile: i.mobile,
                }))
              : []
          }
          onChange={(event, value) => {
            setBuyerSelected(value.id);
            setBuyerItem(value.item);
            if (payerValue === "buyer") {
              formikPayer.setFieldValue("mobile", value.mobile);
            }
          }}
          renderInput={(params) => (
            <TextField {...params} label="انتخاب خریدار" />
          )}
        />
        <Grid
          container
          xs={12}
          style={{
            borderStyle: "solid",
            borderWidth: "2px",
            borderColor: "red",
            borderRadius: "10px",
            padding: "5px",
          }}
          alignItems="center"
        >
          <Typography variant="body2" color="primary">
            خریدار:{"‌ ‌"}
          </Typography>
          {buyerItem ? (
            <Typography variant="body2">
              {" "}
              {buyerItem?.fullname} ({buyerItem?.mobile})
            </Typography>
          ) : (
            <Typography variant="body2">
              {" "}
              {item?.outProvincePoultryRequestBuyer?.fullname} (
              {item?.outProvincePoultryRequestBuyer?.mobile})
            </Typography>
          )}
        </Grid>
        <Grid
          container
          xs={12}
          alignItems="center"
          justifyContent="center"
          gap={SPACING.SMALL}
        >
          <IconButton
            color={submitDriver ? "error" : "primary"}
            onClick={() => {
              setSubmitDriver(!submitDriver);
            }}
          >
            <Typography
              variant="body1"
              color={submitDriver ? "error" : "primary"}
            >
              {" "}
              افزودن اطلاعات خودرو
            </Typography>

            {submitDriver ? <RemoveIcon /> : <AddIcon />}
          </IconButton>
          {submitDriver && (
            <Grid
              container
              xs={12}
              alignItems="center"
              justifyContent="center"
              gap={SPACING.SMALL}
            >
              <Typography variant="body1">اطلاعات خودرو حمل</Typography>
              <TextField
                label="نام و نام خانوادگی راننده"
                name="driverName"
                value={formikDriver.values.driverName}
                onChange={formikDriver.handleChange}
                error={
                  formikDriver.touched.driverName &&
                  Boolean(formikDriver.errors.driverName)
                }
                helperText={
                  formikDriver.touched.driverName &&
                  formikDriver.errors.driverName
                }
                required
                fullWidth
              />
              <TextField
                label="تلفن راننده"
                name="driverMobile"
                value={formikDriver.values.driverMobile}
                onChange={formikDriver.handleChange}
                error={
                  formikDriver.touched.driverMobile &&
                  Boolean(formikDriver.errors.driverMobile)
                }
                helperText={
                  formikDriver.touched.driverMobile &&
                  formikDriver.errors.driverMobile
                }
                required
                fullWidth
              />
              <TextField
                label="مدل خودرو"
                name="driverCar"
                value={formikDriver.values.driverCar}
                onChange={formikDriver.handleChange}
                error={
                  formikDriver.touched.driverCar &&
                  Boolean(formikDriver.errors.driverCar)
                }
                helperText={
                  formikDriver.touched.driverCar &&
                  formikDriver.errors.driverCar
                }
                type="tel"
                required
                fullWidth
              />
              <CarPelak width="100%" handleChange={carPelakHandleChange} />
              <TextField
                label="کد بهداشتی حمل"
                name="driverhealthCode"
                value={formikDriver.values.driverhealthCode}
                onChange={formikDriver.handleChange}
                error={
                  formikDriver.touched.driverhealthCode &&
                  Boolean(formikDriver.errors.driverhealthCode)
                }
                helperText={
                  formikDriver.touched.driverhealthCode &&
                  formikDriver.errors.driverhealthCode
                }
                required
                fullWidth
              />
            </Grid>
          )}
        </Grid>
        {wageType && (
          <>
            <FormControl>
              <FormLabel id="demo-controlled-radio-buttons-group">
                پرداخت کننده
              </FormLabel>
              <RadioGroup
                row
                aria-labelledby="demo-controlled-radio-buttons-group"
                name="controlled-radio-buttons-group"
                value={payerValue}
                onChange={handleChangePayer}
              >
                <FormControlLabel
                  value="poultry"
                  control={<Radio />}
                  label="مرغدار"
                />
                <FormControlLabel
                  value="buyer"
                  control={<Radio />}
                  label="خریدار"
                />
              </RadioGroup>
            </FormControl>
            <Grid
              container
              xs={12}
              alignItems="center"
              justifyContent="center"
              mt={1}
              p={1}
              gap={1}
              style={{
                borderStyle: "solid",
                borderWidth: "2px",
                borderColor: "gray",
                borderRadius: "5px",
              }}
            >
              <Typography variant="body2" color="error">
                از این قسمت میتوانید تلفن{" "}
                {payerValue === "poultry" ? "مرغدار" : "خریدار"} را ویرایش کنید.
              </Typography>
              <TextField
                fullWidth
                disabled
                id="mobile"
                value={formikPayer.values.mobile}
                error={
                  formikPayer.touched.mobile
                    ? Boolean(formikPayer.errors.mobile)
                    : null
                }
                onChange={formikPayer.handleChange}
                onBlur={formikPayer.handleBlur}
                helperText={
                  formikPayer.touched.mobile &&
                  Boolean(formikPayer.errors.mobile)
                    ? formikPayer.errors.mobile
                    : null
                }
                label="موبایل"
                autoComplete="current-password"
                variant="outlined"
              />
            </Grid>
          </>
        )}
        <Grid mb={SPACING.SMALL}>
          <Button
            fullWidth
            variant="contained"
            disabled={!isFormValid()}
            onClick={() => {
              dispatch(
                provinceFreeSaleEditRequestService({
                  edit: true,
                  quantity: formik.values.noChicken,
                  Index_weight: parseInt(formik.values.weight),
                  poultry_request_key: item?.key,
                  out_province_driver_info: {
                    driverName: !submitDriver
                      ? null
                      : formikDriver.values.driverName,
                    driverMobile: !submitDriver
                      ? null
                      : formikDriver.values.driverMobile,
                    driverCar: !submitDriver
                      ? null
                      : formikDriver.values.driverCar,
                    driverPelak: !submitDriver
                      ? null
                      : driverPelak[0] +
                        " " +
                        driverPelak[1] +
                        " " +
                        driverPelak[2] +
                        " " +
                        driverPelak[3],
                    driverhealthCode: !submitDriver
                      ? null
                      : formikDriver.values.driverhealthCode,
                  },
                  out_province_poultry_request_buyer_key: buyerSelected,

                  poultry_mobile:
                    payerValue === "poultry" ? formikPayer.values.mobile : null,
                  buyer_mobile:
                    payerValue === "buyer" ? formikPayer.values.mobile : null,
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  fetchApiData(1);
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            ویرایش درخواست
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};
