import {
  Autocomplete,
  Button,
  FormControl,
  FormControlLabel,
  InputAdornment,
  Radio,
  RadioGroup,
  TextField,
} from "@mui/material";
import { SPACING } from "../../../data/spacing";
import { Grid } from "../../../components/grid/Grid";
import { DRAWER } from "../../../lib/redux/slices/appSlice";
import { stewardSegmentSubmitService } from "../services/steward-segment-submit-service";
import { useDispatch, useSelector } from "react-redux";
import { useContext, useEffect, useState, useCallback } from "react";
import { AppContext } from "../../../contexts/AppContext";
import { useFormik } from "formik";
import { Yup } from "../../../lib/yup/yup";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";
import { stewardEditSegmentService } from "../services/steward-segment-edit-operation";
import MonthlyDataCalendar from "../../../components/date-picker/MonthlyDataCalendar";
import PersianDate from "persian-date";
import axios from "axios";
import { LabelField } from "../../../components/label-field/LabelField";
import { checkPathStartsWith } from "../../../utils/checkPathStartsWith";
import {
  slaughterGetGuildsForAllocateService,
  slaughterGetStewardsForAllocateService,
} from "../../slaughter-house/services/slaughter-get-guilds-for-allocate";
import { Typography } from "@mui/material";

const getValidationSchema = (selectedDateAmount) =>
  Yup.object().shape({
    weight: Yup.number()
      .required("وزن لاشه الزامی است")
      .min(0.01, "وزن باید بیشتر از 0 باشد")
      .test(
        "max-production-date-amount",
        `وزن نمی‌تواند بیشتر از موجودی تاریخ تولید (${
          selectedDateAmount?.toLocaleString() || 0
        } کیلوگرم) باشد!`,
        function (value) {
          if (!selectedDateAmount || selectedDateAmount === null) return true;
          return value <= selectedDateAmount;
        }
      ),
    product_key: Yup.string().when("segmentType", {
      is: "own",
      then: Yup.string().required("انتخاب کلید الزامی است"),
    }),
  });

export const StewardSegmentSubmitOperation = ({
  updateTable,
  productKey,
  editData,
  item,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [segmentType, setSegmentType] = useState("own");
  const [selectedInventory] = useState("free");
  const [approvedStatus, setApprovedStatus] = useState("governmental");
  const [buyerCategory, setBuyerCategory] = useState(""); // "stewards" or "guilds"
  const [guildsData, setGuildsData] = useState([]);
  const [stewardsData, setStewardsData] = useState([]);
  const [buyerData, setBuyerData] = useState({
    key: "",
    item: "",
    buyerType: "",
    allocationType: "",
  });
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const [selectedCalendarDate, setSelectedCalendarDate] = useState(null);
  const [calendarDayData, setCalendarDayData] = useState({});
  const [productionDate, setProductionDate] = useState(null);
  const [selectedDateAmount, setSelectedDateAmount] = useState(null);
  const [calendarRawData, setCalendarRawData] = useState({
    governmental: [],
    free: [],
  });

  const formik = useFormik({
    initialValues: {
      product_key: productKey || editData?.productkey || "",
      weight: editData?.weight || "",
      segmentType: editData ? (editData?.guildkey ? "free" : "own") : "own",
    },
    validationSchema: getValidationSchema(selectedDateAmount),
    onSubmit: (values) => {
      if (editData) {
        const req = {
          weight: values.weight,
          key: item?.key,
        };

        dispatch(stewardEditSegmentService(req)).then((r) => {
          if (r.payload?.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(DRAWER({ right: false, bottom: false, content: null }));
            updateTable();
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      } else {
        let req;

        if (segmentType === "own") {
          req = {
            product_key: values?.product_key,
            weight: values.weight,
            sale_type: selectedInventory,
            quota: approvedStatus,
            production_date: productionDate,
            distribution_type: "web",
          };
        } else {
          if (!buyerData?.key) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "لطفا مباشر یا صنف را انتخاب کنید",
              severity: "error",
            });
            return;
          }

          req = {
            guild_key: buyerData?.buyerType === "Guild" ? buyerData?.key : null,
            steward_key:
              buyerData?.buyerType === "Steward" ? buyerData?.key : null,
            weight: values.weight,
            product_key: productKey || "",
            sale_type: selectedInventory,
            quota: approvedStatus,
            production_date: productionDate,
            distribution_type: "web",
          };
          req = Object.fromEntries(
            Object.entries(req).filter(([, val]) => val !== null)
          );
        }
        req.role_key = selectedSubUser?.key;

        dispatch(stewardSegmentSubmitService(req)).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(DRAWER({ right: false, bottom: false, content: null }));
            updateTable();
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      }
    },
  });

  const handleSegmentTypeChange = (event) => {
    const newType = event.target.value;
    setSegmentType(newType);
    formik.setFieldValue("segmentType", newType);
  };

  // const handleSellType = (event) => {
  //   const newType = event.target.value;
  //   setSelectedInventory(newType);
  // };

  const handleApprovedPrice = (event) => {
    const newType = event.target.value;
    setApprovedStatus(newType);
  };

  const handleBuyerCategoryChange = (event) => {
    const newCategory = event.target.value;
    setBuyerCategory(newCategory);
    setBuyerData({
      key: "",
      item: "",
      buyerType: "",
      allocationType: "",
    });
    setGuildsData([]);
    setStewardsData([]);
  };

  // Calendar functions
  const handleDateSelect = (dateInfo) => {
    if (dateInfo && dateInfo.formattedDate) {
      setSelectedCalendarDate(dateInfo.formattedDate);

      // Get the data for the selected date
      const data = calendarDayData[dateInfo.formattedDate];

      if (data && data.originalDay) {
        setProductionDate(data.originalDay);
      }

      // Get the amount for the selected date
      if (data && data.value1 !== undefined) {
        setSelectedDateAmount(data.value1);
      } else {
        setSelectedDateAmount(null);
      }
    }
  };

  const transformCalendarData = useCallback((dataArray) => {
    if (!Array.isArray(dataArray)) return {};

    const transformedData = {};
    dataArray.forEach((item) => {
      if (item.day && item.amount !== undefined) {
        const persianDate = new PersianDate(new Date(item.day));
        const persianDateStr = persianDate.format("YYYY/MM/DD");
        transformedData[persianDateStr] = {
          value1: item.amount,
          originalDay: item.day,
          active: item.active === true,
        };
      }
    });
    return transformedData;
  }, []);

  const updateCalendarData = useCallback(
    (dataArray) => {
      const transformed = transformCalendarData(dataArray);
      setCalendarDayData(transformed);
    },
    [transformCalendarData]
  );

  // Fetch calendar data from API
  const fetchCalendarData = useCallback(async () => {
    try {
      const currentRole = getRoleFromUrl();
      let remainWeightEndpoint = "kill-house-remain-weight";
      if (currentRole === "Steward") {
        remainWeightEndpoint = "steward-remain-weight";
      } else if (currentRole === "Guilds") {
        remainWeightEndpoint = "guild-remain-weight";
      }

      const response = await axios.get(`${remainWeightEndpoint}/`, {
        params: {
          role_key:
            checkPathStartsWith("slaughter") ||
            checkPathStartsWith("steward") ||
            checkPathStartsWith("senf")
              ? selectedSubUser?.key || ""
              : "",
        },
      });
      if (response.data) {
        setCalendarRawData({
          governmental: response.data.governmental || [],
          free: response.data.free || [],
        });
        const dataToShow =
          approvedStatus === "governmental"
            ? response.data.governmental
            : response.data.free;
        updateCalendarData(dataToShow);
      }
    } catch (error) {
      console.error("Error fetching calendar data:", error);
    }
  }, [approvedStatus, updateCalendarData, selectedSubUser]);

  useEffect(() => {
    fetchCalendarData();
  }, []);

  useEffect(() => {
    if (!editData && buyerCategory) {
      if (buyerCategory === "guilds") {
        dispatch(
          slaughterGetGuildsForAllocateService({
            free: true,
            role_key:
              checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
                ? selectedSubUser?.key || ""
                : "",
          })
        ).then((r) => {
          setGuildsData(r.payload.data || []);
        });
      } else if (buyerCategory === "stewards") {
        dispatch(
          slaughterGetStewardsForAllocateService({
            free: true,
            role_key:
              checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
                ? selectedSubUser?.key || ""
                : "",
          })
        ).then((r) => {
          setStewardsData(r.payload.data || []);
        });
      }
    }
  }, [buyerCategory, selectedSubUser?.key, editData]);

  useEffect(() => {
    if (
      calendarRawData.governmental.length > 0 ||
      calendarRawData.free.length > 0
    ) {
      const dataToShow =
        approvedStatus === "governmental"
          ? calendarRawData.governmental
          : calendarRawData.free;
      updateCalendarData(dataToShow);
      setSelectedCalendarDate(null);
      setProductionDate(null);
      setSelectedDateAmount(null);
    }
  }, [approvedStatus, calendarRawData, updateCalendarData]);

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

  // Set segmentType to "own" for Guilds role
  useEffect(() => {
    const currentRole = getRoleFromUrl();
    if (currentRole === "Guilds" && !editData) {
      setSegmentType("own");
      formik.setFieldValue("segmentType", "own");
    }
  }, [editData]);

  return (
    <Grid container direction="column" justifyContent="center" gap={2}>
      <Grid container direction="column" justifyContent="center" gap={2} pt={2}>
        <form
          onSubmit={formik.handleSubmit}
          style={{
            display: "flex",
            flexDirection: "column",
            gap: SPACING.LARGE + 4,
          }}
        >
          {!editData && getRoleFromUrl() !== "Guilds" && (
            <LabelField label="قطعه بندی (کاربر)">
              <FormControl>
                <RadioGroup
                  row
                  aria-labelledby="segment-type-radio-group"
                  name="segmentType"
                  value={segmentType}
                  onChange={handleSegmentTypeChange}
                  sx={{
                    justifyContent: "space-between",
                  }}
                >
                  <FormControlLabel
                    value="own"
                    control={<Radio />}
                    label="قطعه بندی (کاربر)"
                  />
                  <FormControlLabel
                    value="free"
                    control={<Radio />}
                    label="تخصیص به قطعه بند"
                  />
                </RadioGroup>
              </FormControl>
            </LabelField>
          )}

          {!editData && segmentType === "free" && (
            <>
              <LabelField label="خریداران">
                <FormControl fullWidth>
                  <RadioGroup
                    row
                    aria-labelledby="buyer-category-radio-group"
                    name="buyerCategory"
                    value={buyerCategory}
                    onChange={handleBuyerCategoryChange}
                    sx={{
                      justifyContent: "space-between",
                    }}
                  >
                    <FormControlLabel
                      value="stewards"
                      control={<Radio />}
                      label="مباشرین"
                    />
                    <FormControlLabel
                      value="guilds"
                      control={<Radio />}
                      label="اصناف"
                    />
                  </RadioGroup>
                </FormControl>
              </LabelField>

              {buyerCategory && (
                <Grid xs={12} container>
                  {(() => {
                    const currentData =
                      buyerCategory === "guilds" ? guildsData : stewardsData;
                    const isEmpty = !currentData || currentData.length === 0;

                    if (isEmpty) {
                      return (
                        <Typography
                          variant="body2"
                          color="text.secondary"
                          sx={{
                            width: "100%",
                            textAlign: "center",
                            padding: 2,
                            fontStyle: "italic",
                          }}
                        >
                          {buyerCategory === "guilds"
                            ? "هیچ صنفی یافت نشد"
                            : "هیچ مباشری یافت نشد"}
                        </Typography>
                      );
                    }

                    return (
                      <Autocomplete
                        fullWidth
                        disablePortal
                        id="buyer-selection"
                        options={
                          buyerCategory === "guilds"
                            ? guildsData.map((i) => {
                                return {
                                  data: i,
                                  label: `${i?.guildsName} ${i?.user?.fullname} (${i?.user?.mobile})`,
                                };
                              })
                            : stewardsData.map((i) => {
                                return {
                                  data: i,
                                  label: `${i?.name || ""} - ${
                                    i?.user?.fullname || ""
                                  } (${i?.user?.mobile || ""})`,
                                };
                              })
                        }
                        onChange={(event, value) => {
                          if (buyerCategory === "guilds") {
                            setBuyerData({
                              item: value?.data,
                              key: value?.data?.key,
                              allocationType: value?.data?.steward
                                ? "steward_steward"
                                : "steward_guild",
                              buyerType: value?.data?.steward
                                ? "Steward"
                                : "Guild",
                            });
                          } else if (buyerCategory === "stewards") {
                            setBuyerData({
                              item: value?.data,
                              key: value?.data?.key,
                              allocationType: "steward_steward",
                              buyerType: "Steward",
                            });
                          }
                        }}
                        renderInput={(params) => (
                          <TextField
                            fullWidth
                            {...params}
                            label={
                              buyerCategory === "guilds"
                                ? "انتخاب صنف"
                                : "انتخاب مباشر"
                            }
                          />
                        )}
                      />
                    );
                  })()}
                </Grid>
              )}
            </>
          )}

          {/* {!editData && (
            <LabelField label="نوع فروش">
              <FormControl>
                <RadioGroup
                  row
                  aria-labelledby="segment-type-radio-group"
                  name="segmentType"
                  value={selectedInventory}
                  onChange={handleSellType}
                  sx={{
                    justifyContent: "space-between",
                  }}
                >
                  <FormControlLabel
                    disabled
                    value="governmental"
                    control={<Radio />}
                    label="قیمت دولتی"
                  />
                  <FormControlLabel
                    value="free"
                    control={<Radio />}
                    label="قیمت آزاد"
                  />
                </RadioGroup>
              </FormControl>
            </LabelField>
          )} */}
          {!editData && (
            <LabelField label="نوع انبار">
              <FormControl>
                <RadioGroup
                  row
                  aria-labelledby="segment-type-radio-group"
                  name="segmentType"
                  value={approvedStatus}
                  onChange={handleApprovedPrice}
                  sx={{
                    justifyContent: "space-between",
                  }}
                >
                  <FormControlLabel
                    value="governmental"
                    control={<Radio />}
                    label="دولتی"
                  />
                  <FormControlLabel
                    value="free"
                    control={<Radio />}
                    label="آزاد"
                  />
                </RadioGroup>
              </FormControl>
            </LabelField>
          )}
          {!editData && (
            <Grid
              style={{ width: "100%" }}
              container
              xs={12}
              lg={3}
              justifyContent="center"
              alignItems="center"
              gap={1}
            >
              <MonthlyDataCalendar
                onDateSelect={handleDateSelect}
                dayData={calendarDayData}
                selectedDate={selectedCalendarDate}
                label={`تاریخ تولید گوشت ${
                  selectedDateAmount !== null
                    ? `(موجودی: ${selectedDateAmount?.toLocaleString()} کیلوگرم)`
                    : ""
                }`}
              />
            </Grid>
          )}

          <TextField
            id="weight"
            name="weight"
            label="وزن لاشه"
            type="number"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">کیلوگرم</InputAdornment>
              ),
            }}
            value={formik.values.weight}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              (formik.touched.weight && Boolean(formik.errors.weight)) ||
              (selectedDateAmount && formik.values.weight > selectedDateAmount)
            }
            helperText={
              selectedDateAmount && formik.values.weight > selectedDateAmount
                ? `وزن نمی‌تواند بیشتر از موجودی تاریخ تولید (${selectedDateAmount?.toLocaleString()} کیلوگرم) باشد!`
                : formik.touched.weight && formik.errors.weight
            }
            fullWidth
          />

          <Grid container spacing={2}>
            <Grid xs={6}>
              <Button
                type="submit"
                fullWidth
                variant="contained"
                color="primary"
                disabled={
                  !editData &&
                  (!productionDate ||
                    (selectedDateAmount &&
                      formik.values.weight > selectedDateAmount) ||
                    (segmentType === "free" && !buyerData?.key))
                }
              >
                {editData ? "ویرایش" : "ثبت"}
              </Button>
            </Grid>
            <Grid xs={6}>
              <Button
                fullWidth
                variant="outlined"
                color="primary"
                onClick={() => {
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                }}
              >
                انصراف
              </Button>
            </Grid>
          </Grid>
        </form>
      </Grid>
    </Grid>
  );
};
