import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  Autocomplete,
  Button,
  Paper,
  Stack,
  TextField,
  Typography,
} from "@mui/material";

import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch, useSelector } from "react-redux";
import { slaughterGetPoultriesService } from "../../../slaughter-house/services/salughter-get-poultries";
import { avicultureGetHatchingData } from "../../../aviculture/services/aviculture-get-hatching-data";
import { slaughterGetKillerKillhousesService } from "../../../slaughter-house/services/slaughter-get-killers-killhouses";
import { slaughterGetKillhousesService } from "../../../slaughter-house/services/slaughter-get-killhouses";
import {
  provinceEditBarDifferenceService,
  provinceGetBarDifferenceInfoService,
  provinceSubmitBarDifferenceService,
} from "../../services/province-bar-differences-services";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { resizeImage } from "../../../../utils/resizeImage";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ProvinceSubmitBarDifference = ({ updateTable, isEdit, item }) => {
  const [poultryData, setPoultryData] = useState("");
  const [openNotif] = useContext(AppContext);
  const [selectedPolutry, setSelectedPolutry] = useState("");
  const [profileImages, setProfileImages] = useState([]);
  const [diffInfo, setDiffInfo] = useState(null);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const dispatch = useDispatch();
  const { slaughterGetPoultries, slaughterGetKillhouses } = useSelector(
    (state) => state.slaughterSlice
  );

  useEffect(() => {
    if (!isEdit) {
      dispatch(
        slaughterGetPoultriesService({
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      );
      dispatch(
        slaughterGetKillerKillhousesService({
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      );
      dispatch(
        slaughterGetKillhousesService({
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      );
    }
  }, [selectedSubUser?.key]);

  const initialValues = {
    killhouse: null,
    killerPlace: null,
    poultry: null,
    hatching_key: null,
    quantity: parseInt(item?.quantity) || null,
    difference_image: null,
    register_message: item?.registerMessage || null,
  };

  const validationSchema = Yup.object().shape({
    killhouse: Yup.string("")
      .typeError("این فیلد الزامی است")
      .required("این فیلد الزامی است"),
    poultry: Yup.string("")
      .typeError("این فیلد الزامی است")
      .required("این فیلد الزامی است"),
    poultryPrice: Yup.number().typeError("لطفا فیلد را به درستی وارد کنید!"),
    hatching_key: Yup.string().required("این فیلد الزامی است"),
    quantity: Yup.number()
      .required("این فیلد الزامی است")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
  });

  const formik = useFormik({
    initialValues,
    validationSchema,
  });

  useEffect(() => {
    if (formik.values.poultry) {
      dispatch(
        avicultureGetHatchingData({
          key: formik.values.poultry,
        })
      ).then((r) => {
        setPoultryData(r.payload.data);
      });
    }
  }, [formik.values.poultry, selectedSubUser?.key]);

  useEffect(() => {
    formik.validateForm();
  }, [formik.values.quantity, dispatch]);

  const factorPaymentHandler = (imageList) => {
    if (imageList.length === 0) {
      formik.setFieldValue("difference_image", []);
      setProfileImages([]);
    } else {
      const resizedImagesPromises = imageList.map(
        (image) =>
          new Promise((resolve) => {
            const file = image.file;
            resizeImage(file, (resizedDataUrl) => {
              resolve(fixBase64(resizedDataUrl));
            });
          })
      );

      Promise.all(resizedImagesPromises).then((resizedImages) => {
        formik.setFieldValue("difference_image", resizedImages);
        setProfileImages(imageList);
      });
    }
  };

  useEffect(() => {
    if (formik.values.hatching_key && formik.values.killhouse) {
      dispatch(
        provinceGetBarDifferenceInfoService({
          hatching_key: formik.values.hatching_key,
          kill_house_key: formik.values.killhouse,
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      ).then((r) => {
        setDiffInfo(r.payload.data);
      });
    }
  }, [
    formik.values.hatching_key,
    formik.values.killhouse,
    selectedSubUser?.key,
  ]);

  return (
    <Grid container direction="column" gap={SPACING.SMALL}>
      {!isEdit && (
        <>
          {slaughterGetPoultries?.length ? (
            <Autocomplete
              id="poultry"
              disableClearable={true}
              options={slaughterGetPoultries?.map((item) => {
                return {
                  label: `${item.unitName} (${item.user?.fullname})`,
                  value: item.key,
                  item,
                };
              })}
              getOptionLabel={(option) => option.label}
              onChange={(_, value) => {
                formik.setFieldValue("poultry", value.item.key);
              }}
              onBlur={formik.handleBlur}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="انتخاب مرغداری"
                  variant="outlined"
                  error={
                    formik.touched.poultry && Boolean(formik.errors.poultry)
                  }
                  helperText={formik.touched.poultry && formik.errors.poultry}
                />
              )}
            />
          ) : (
            <Typography color="error" variant="body2">
              موردی یافت نشد!
            </Typography>
          )}

          {poultryData && (
            <Grid minWidth={210}>
              <Autocomplete
                disablePortal
                disabled={!formik.values.poultry}
                id="combo-box-demo"
                options={poultryData?.map((item) => {
                  return {
                    label: `${item?.poultry.unitName}`,
                    value: item.key,
                    item,
                  };
                })}
                onChange={(event, value) => {
                  setSelectedPolutry(value.item);
                  formik.setFieldValue("hatching_key", value.value);
                }}
                renderInput={(params) => (
                  <TextField {...params} label="محل پرورش" />
                )}
              />
            </Grid>
          )}

          {selectedPolutry && (
            <>
              <Grid container direction="column" justifyContent="space-between">
                <Grid container gap={SPACING.TINY}>
                  <Typography>نام و نام خانوادگی:</Typography>
                  <Typography>
                    {selectedPolutry?.poultry?.userprofile?.fullName}
                  </Typography>
                </Grid>
                <Grid container gap={SPACING.TINY}>
                  <Typography>تلفن:</Typography>
                  <Typography>
                    {selectedPolutry?.poultry?.userprofile?.mobile}
                  </Typography>
                </Grid>
                <Grid container gap={SPACING.TINY}>
                  <Typography>آدرس:</Typography>
                  <Typography>
                    {`شهر ${selectedPolutry.poultry?.address?.city?.name}  ${
                      selectedPolutry?.poultry?.address?.address
                        ? "-" + selectedPolutry?.poultry?.address?.address
                        : ""
                    }`}
                  </Typography>
                </Grid>
                <Grid container gap={SPACING.TINY}>
                  <Typography>سن جوجه:</Typography>
                  <Typography>{selectedPolutry?.chickenAge} روز</Typography>
                </Grid>
                <Grid container gap={SPACING.TINY}>
                  <Typography>مانده در سالن:</Typography>
                  <Typography>
                    {selectedPolutry?.leftOver?.toLocaleString()} قطعه
                  </Typography>
                </Grid>
                <Grid container gap={SPACING.TINY}>
                  <Typography color="error">مانده فروش آزاد:</Typography>
                  <Typography color="error">
                    {selectedPolutry?.freeGovernmentalInfo?.leftTotalFreeCommitmentQuantity?.toLocaleString()}{" "}
                    قطعه
                  </Typography>
                </Grid>
                <Grid container gap={SPACING.TINY}>
                  <Typography>نژاد:</Typography>
                  <Typography>{selectedPolutry?.chickenBreed}</Typography>
                </Grid>
              </Grid>
              {slaughterGetKillhouses?.length && (
                <Autocomplete
                  id="killhouse"
                  disableClearable={true}
                  options={slaughterGetKillhouses?.map((item) => {
                    const buyerNamePrefix = item?.killer
                      ? "کشتارکن"
                      : "کشتارگاه";
                    return {
                      label: buyerNamePrefix + " " + item.name,
                      value: item.key,
                      killer: item.killer,
                      item: item,
                      // disabled: item.allowDirectBuying,
                    };
                  })}
                  // getOptionDisabled={(option) => !option.disabled}
                  getOptionLabel={(option) => option.label}
                  onChange={(_, value) => {
                    formik.setFieldValue("killhouse", value.value);
                  }}
                  onBlur={formik.handleBlur}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="انتخاب کشتارگاه/کشتارکن"
                      variant="outlined"
                      error={
                        formik.touched.killhouse &&
                        Boolean(formik.errors.killhouse)
                      }
                      helperText={
                        formik.touched.killhouse && formik.errors.killhouse
                      }
                    />
                  )}
                />
              )}
              {diffInfo && (
                <Paper elevation={3} sx={{ p: 1, borderRadius: 2 }}>
                  <Stack spacing={1}>
                    <Typography
                      variant="body2"
                      fontWeight={500}
                      color="text.primary"
                    >
                      حجم کم شده از سالن مرغدار:{" "}
                      <Typography
                        component="span"
                        variant="body1"
                        color="primary"
                        fontWeight={600}
                      >
                        {diffInfo.totalQuantity?.toLocaleString()} قطعه
                      </Typography>
                    </Typography>
                    <Typography
                      variant="body2"
                      fontWeight={500}
                      color="text.primary"
                    >
                      وزن تقریبی کشتار:{" "}
                      <Typography
                        component="span"
                        variant="body1"
                        color="primary"
                        fontWeight={600}
                      >
                        {diffInfo.totalWeight?.toLocaleString()} کیلوگرم
                      </Typography>
                    </Typography>
                    <Typography
                      variant="body2"
                      fontWeight={500}
                      color="text.primary"
                    >
                      حجم سفارشات دریافتی توسط کشتارگاه:
                      <Typography
                        component="span"
                        variant="body2"
                        color="primary"
                        fontWeight={600}
                      >
                        {diffInfo.firstTotalQuantity?.toLocaleString()} قطعه
                      </Typography>
                    </Typography>
                    <Typography
                      variant="body2"
                      fontWeight={500}
                      color="text.primary"
                    >
                      اختلاف کشتار(حجم):
                      <Typography
                        component="span"
                        variant="body1"
                        color="primary"
                        fontWeight={600}
                      >
                        {diffInfo.differenceQuantity?.toLocaleString()} قطعه
                      </Typography>
                    </Typography>
                  </Stack>
                </Paper>
              )}
            </>
          )}
        </>
      )}

      {(isEdit || selectedPolutry) && (
        <>
          <TextField
            label="حجم (قطعه)"
            variant="outlined"
            fullWidth
            type="text"
            name="quantity"
            id="quantity"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.quantity}
            error={formik.touched.quantity && Boolean(formik.errors.quantity)}
            helperText={formik.touched.quantity && formik.errors.quantity}
          />

          <ImageUpload
            onChange={factorPaymentHandler}
            images={profileImages}
            maxNumber={1}
            title={"سند"}
          />
          <TextField
            label="توضیحات"
            name="register_message"
            id="register_message"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.register_message}
            minRows={2}
            maxRows={6}
            sx={{
              width: "100%",
              "& .MuiInputBase-root": {
                height: 150,
              },
            }}
          />

          <Button
            disabled={isEdit ? !formik.values.quantity : !formik.isValid}
            fullWidth
            variant="contained"
            onClick={() => {
              if (isEdit) {
                dispatch(
                  provinceEditBarDifferenceService({
                    bar_key: item?.key,
                    quantity: formik.values.quantity,
                    register_message: formik.values.register_message,
                    images: formik.values.difference_image,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مشکلی پیش آمده است!",
                      severity: "error",
                    });
                  } else {
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                    dispatch(
                      DRAWER({
                        right: false,
                        bottom: false,
                        content: null,
                      })
                    );
                  }
                });
              } else {
                dispatch(
                  provinceSubmitBarDifferenceService({
                    hatching_key: formik.values.hatching_key,
                    kill_house_key: formik.values.killhouse,
                    quantity: formik.values.quantity,
                    register_message: formik.values.register_message,
                    images: formik.values.difference_image,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مشکلی پیش آمده است!",
                      severity: "error",
                    });
                  } else {
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                    dispatch(
                      DRAWER({
                        right: false,
                        bottom: false,
                        content: null,
                      })
                    );
                  }
                });
              }
            }}
          >
            ثبت
          </Button>
        </>
      )}
    </Grid>
  );
};
