import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useFormik } from "formik";
import moment from "moment";
import { Autocomplete, Button, InputAdornment, TextField } from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterGetProductsService } from "../../../slaughter-house/services/slaughter-inventory-gets";
import {
  slaughterGetCitiesService,
  slaughterGetProvinceService
} from "../../../slaughter-house/services/slaughter-get-provinces";
import { fixBase64 } from "../../../../utils/toBase64";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import {
  stewardEditFreeBarService,
  stewardSubmitFreeBarService
} from "../../../guild/services/steward-submit-free-bar-service";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

const ValidationSchema = Yup.object().shape({
  kill_house_name: Yup.string().required("نام فروشنده الزامی است"),
  kill_house_mobile: Yup.string()
    .required("شماره موبایل فروشنده الزامی است")
    .min(11, "شماره موبایل باید دقیقاً 11 رقم باشد")
    .max(11, "شماره موبایل باید دقیقاً 11 رقم باشد"),
  province: Yup.string().required("استان الزامی است"),
  city: Yup.string().required("شهر الزامی است"),
  bar_image: Yup.string().when("$isEdit", {
    is: true,
    then: Yup.string(),
    otherwise: Yup.string().required("عکس بار الزامی است")
  }),
  number_of_carcasses: Yup.number()
    .required("حجم لاشه الزامی است")
    .min(1, "حجم لاشه باید بیشتر از 0 باشد"),
  weight_of_carcasses: Yup.number()
    .required("وزن لاشه الزامی است")
    .min(0.01, "وزن باید بیشتر از 0 باشد"),
  product_key: Yup.string().required("انتخاب محصول الزامی است")
});

export const StewardSubmitFreeBar = ({ updateTable, item }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [productData, setProductData] = useState([]);
  const [provinceData, setProvinceData] = useState([]);
  const [cityData, setCityData] = useState([]);
  const [profileImages, setProfileImages] = useState([]);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  useEffect(() => {
    dispatch(
      slaughterGetProductsService({
        role_key: checkPathStartsWith("steward")
          ? selectedSubUser?.key || ""
          : ""
      })
    ).then((r) => {
      // Handle both direct array response and nested data response
      const data = r.payload?.data;
      if (Array.isArray(data)) {
        setProductData(data);
      } else if (data?.data && Array.isArray(data.data)) {
        setProductData(data.data);
      } else {
        setProductData([]);
      }
    });
    dispatch(slaughterGetProvinceService()).then((r) => {
      setProvinceData(r.payload.data);
    });
  }, [dispatch, selectedSubUser]);
  const formik = useFormik({
    initialValues: {
      product_key: item?.productKey || "",
      kill_house_name: item?.killHouseName || "",
      kill_house_mobile: item?.killHouseMobile || "",
      province: item?.province || "",
      city: item?.city || "",
      bar_image: item?.barImage || "",
      number_of_carcasses: item?.numberOfCarcasses || "",
      weight_of_carcasses: item?.weightOfCarcasses || "",
      date: item?.date || moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      role_key: checkPathStartsWith("steward")
        ? selectedSubUser?.key || ""
        : "",
      ...(item?.key && { key: item.key })
    },
    validationSchema: ValidationSchema,
    onSubmit: (values) => {
      if (item?.key) {
        if (profileImages.length && profileImages[0]?.data_url) {
          values.bar_image = fixBase64(profileImages[0]?.data_url);
        } else {
          values.bar_image = item.barImage;
        }
      }
      const thenCallback = (r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error"
          });
        } else {
          updateTable();
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: item?.key
              ? "اطلاعات خرید با موفقیت ویرایش شد"
              : "اطلاعات خرید جدید با موفقیت ثبت شد",
            severity: "success"
          });
        }
      };

      if (item?.key) {
        dispatch(stewardEditFreeBarService(values)).then(thenCallback);
      } else {
        dispatch(stewardSubmitFreeBarService(values)).then(thenCallback);
      }
    }
  });

  const factorPaymentHandler = (imageList) => {
    if (imageList[0]) {
      formik.setFieldValue("bar_image", fixBase64(imageList[0]?.data_url));
    }
    setProfileImages(imageList);
  };

  useEffect(() => {
    if (formik.values.province) {
      dispatch(slaughterGetCitiesService(formik.values.province)).then((r) => {
        setCityData(r.payload.data);
      });
    }
  }, [formik.values.province]);
  useEffect(() => {
    if (item?.barImage) {
      setProfileImages([{ data_url: item?.barImage }]);
    }
  }, [item]);

  return (
    <Grid container direction="column" justifyContent="center" gap={2}>
      <Grid container direction="column" justifyContent="center" gap={2}>
        <Grid xs={12} container gap={2}>
          <Autocomplete
            fullWidth
            style={{ minWidth: 210 }}
            disablePortal
            id="product_key"
            options={
              Array.isArray(productData) && productData.length > 0
                ? productData.map((i) => ({
                    id: i.key,
                    label: i.name || ""
                  }))
                : []
            }
            value={
              Array.isArray(productData) && productData.length > 0
                ? productData
                    .map((i) => ({ id: i.key, label: i.name || "" }))
                    .find((opt) => opt.id === formik.values.product_key) || null
                : null
            }
            onChange={(event, value) => {
              formik.setFieldValue("product_key", value ? value.id : "");
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                label="انتخاب محصول"
                error={
                  formik.touched.product_key &&
                  Boolean(formik.errors.product_key)
                }
                helperText={
                  formik.touched.product_key && formik.errors.product_key
                }
              />
            )}
          />
        </Grid>

        <form
          onSubmit={formik.handleSubmit}
          style={{
            display: "flex",
            flexDirection: "column",
            gap: SPACING.LARGE
          }}
        >
          <TextField
            id="kill_house_name"
            name="kill_house_name"
            label="نام فروشنده"
            value={formik.values.kill_house_name}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.kill_house_name &&
              Boolean(formik.errors.kill_house_name)
            }
            helperText={
              formik.touched.kill_house_name && formik.errors.kill_house_name
            }
          />

          <TextField
            id="kill_house_mobile"
            name="kill_house_mobile"
            label="تلفن فروشنده"
            value={formik.values.kill_house_mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.kill_house_mobile &&
              Boolean(formik.errors.kill_house_mobile)
            }
            helperText={
              formik.touched.kill_house_mobile &&
              formik.errors.kill_house_mobile
            }
          />
          <Autocomplete
            style={{ width: "100%" }}
            disablePortal
            id="province"
            options={provinceData.map((i) => ({
              id: i.name,
              label: i.name
            }))}
            value={
              formik.values.province
                ? {
                    id: formik.values.province,
                    label: formik.values.province
                  }
                : null
            }
            onChange={(e, value) => {
              formik.setFieldValue("province", value ? value.id : "");
              formik.setFieldValue("city", "");
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                label="استان را انتخاب کنید"
                error={
                  formik.touched.province && Boolean(formik.errors.province)
                }
                helperText={formik.touched.province && formik.errors.province}
              />
            )}
          />

          <Autocomplete
            minWidth={210}
            style={{ width: "100%" }}
            disabled={!formik.values.province}
            disablePortal
            id="city"
            value={
              formik.values.city
                ? {
                    id: formik.values.city,
                    label: formik.values.city
                  }
                : null
            }
            options={
              cityData
                ? cityData.map((i) => ({ id: i.name, label: i.name }))
                : []
            }
            onChange={(e, value) => {
              formik.setFieldValue("city", value ? value.id : "");
              formik.setFieldValue("city", value ? value.id : "");
            }}
            renderInput={(params) => (
              <TextField {...params} label="شهر را انتخاب کنید" />
            )}
          />

          <TextField
            id="number_of_carcasses"
            name="number_of_carcasses"
            label="حجم لاشه"
            type="number"
            InputProps={{
              endAdornment: <InputAdornment position="end">قطعه</InputAdornment>
            }}
            value={formik.values.number_of_carcasses}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.number_of_carcasses &&
              Boolean(formik.errors.number_of_carcasses)
            }
            helperText={
              formik.touched.number_of_carcasses &&
              formik.errors.number_of_carcasses
            }
          />

          <TextField
            id="weight_of_carcasses"
            name="weight_of_carcasses"
            label="وزن لاشه"
            type="number"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">کیلوگرم</InputAdornment>
              )
            }}
            value={formik.values.weight_of_carcasses}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.weight_of_carcasses &&
              Boolean(formik.errors.weight_of_carcasses)
            }
            helperText={
              formik.touched.weight_of_carcasses &&
              formik.errors.weight_of_carcasses
            }
          />

          <ImageUpload
            onChange={factorPaymentHandler}
            images={profileImages}
            maxNumber={1}
            title={"تصویر بار"}
          />

          {!profileImages.length && item?.barImage && (
            <Grid container justifyContent="center">
              <img style={{ width: "60px" }} alt="bar" src={item?.barImage} />
            </Grid>
          )}

          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            disabled={!formik.isValid}
          >
            {item?.key ? "ویرایش خرید" : "ثبت خرید جدید"}
          </Button>
        </form>
      </Grid>
    </Grid>
  );
};
