import { useContext, useEffect, useState, useCallback, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  Autocomplete,
  Button,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
} from "@mui/material";
import { Field, Form, Formik } from "formik";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { Yup } from "../../../../lib/yup/yup";
import { stewardSellOutGetBuyers } from "../../../guild/services/steward-sell-out-get-buyers";
import { AppContext } from "../../../../contexts/AppContext";
import { stewardGetOutSellService } from "../../../guild/services/steward-get-sell-out-service";
import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import { stewardSellOuutSubmitSell } from "../../../guild/services/steward-sell-out-submit-sell";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { fetchStewardBroadcastAndProducts } from "../../services/handle-fetch-steward-products";
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";

const validationSchema = (selectedDateAmount) =>
  Yup.object({
    weight_of_carcasses: Yup.number()
      .required("وزن لاشه‌ها الزامی است")
      .positive("وزن باید عددی مثبت باشد")
      .test(
        "max-production-date-amount",
        `وزن نمی‌تواند بیشتر از موجودی تاریخ تولید (${
          selectedDateAmount?.toLocaleString() || 0
        } کیلوگرم) باشد!`,
        function (value) {
          if (!selectedDateAmount || selectedDateAmount === null) return true;
          return value <= selectedDateAmount;
        }
      ),

    clearance_code: Yup.string()
      .required("کد قرنطینه الزامی است")
      .matches(
        /^(?=.*[A-Z])(?=.*\d)[A-Z0-9]+$/,
        "کد قرنطینه باید ترکیبی از حروف بزرگ انگلیسی و عدد باشد"
      ),
    date: Yup.date().required("تاریخ الزامی است"),
    production_date: Yup.string().required("تاریخ تولید الزامی است"),
  });

export const StewardSellOutOfProvinceSubmitSell = ({
  updateTable,
  fetchItems,
  isInventory,
}) => {
  const [productData, setProductData] = useState([]);
  const [productKey, setProductKey] = useState(null);
  const [buterData, setBuyerData] = useState([]);
  const [buyerSelected, setBuyerSelected] = useState(null);
  const [selectedInventory] = useState("free");
  const [approvedStatus, setApprovedStatus] = useState("governmental");
  const [selectedCalendarDate, setSelectedCalendarDate] = useState(null);
  const [calendarDayData, setCalendarDayData] = useState({});
  const [productionDate, setProductionDate] = useState(null);
  const [selectedDateAmount, setSelectedDateAmount] = useState(null);
  const [calendarDateError, setCalendarDateError] = useState(null);
  const formikRef = useRef(null);
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const [openNotif] = useContext(AppContext);

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

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

      // Use the original Gregorian date from the API data for production_date
      if (data && data.originalDay) {
        // Prevent choosing a production date after the main form date
        if (
          formikRef.current?.values?.date &&
          moment(data.originalDay).isAfter(
            moment(formikRef.current.values.date),
            "day"
          )
        ) {
          setCalendarDateError(
            "تاریخ تولید نمی‌تواند بعد از تاریخ انتخابی باشد"
          );
          return;
        }
        setCalendarDateError(null);
        setProductionDate(data.originalDay);
        if (formikRef.current) {
          formikRef.current.setFieldValue("production_date", 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) => {
      // Include all items to show amounts, but store active status
      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, // Store active status
        };
      }
    });
    return transformedData;
  }, []);

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

  const [selectedFormDate, setSelectedFormDate] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

  const fetchCalendarData = useCallback(
    async (dateParam = selectedFormDate) => {
      try {
        const response = await axios.get("/steward-remain-weight/", {
          params: {
            date: dateParam,
            role_key: checkPathStartsWith("steward")
              ? selectedSubUser?.key
              : "",
          },
        });
        if (response.data) {
          const dataToShow =
            approvedStatus === "governmental"
              ? response.data.governmental
              : response.data.free;
          updateCalendarData(dataToShow || []);
        }
      } catch (error) {
        console.error("Error fetching calendar data:", error);
      }
    },
    [approvedStatus, updateCalendarData, selectedFormDate, selectedSubUser]
  );

  useEffect(() => {
    dispatch(
      stewardSellOutGetBuyers({
        role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "",
      })
    ).then((r) => {
      setBuyerData(r.payload.data);
    });
  }, [selectedSubUser?.key]);

  useEffect(() => {
    dispatch(
      stewardGetOutSellService({
        role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "",
      })
    ).then((r) => {
      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, selectedSubUser?.key]);

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

  useEffect(() => {
    let dateToUse = selectedFormDate;
    if (approvedStatus === "governmental" && formikRef.current) {
      const today = moment(new Date()).format("YYYY-MM-DD");
      formikRef.current.setFieldValue("date", today);
      setSelectedFormDate(today);
      dateToUse = today;
    }

    fetchCalendarData(dateToUse);
    setSelectedCalendarDate(null);
    setProductionDate(null);
    setSelectedDateAmount(null);
    if (formikRef.current) {
      formikRef.current.setFieldValue("production_date", "");
    }
  }, [
    approvedStatus,
    selectedFormDate,
    fetchCalendarData,
    selectedSubUser?.key,
  ]);

  useEffect(() => {
    if (formikRef.current) {
      formikRef.current.validateForm();
    }
  }, [selectedDateAmount]);

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

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

    if (newType === "governmental" && formikRef.current) {
      const today = moment(new Date()).format("YYYY-MM-DD");
      formikRef.current.setFieldValue("date", today);
      setSelectedFormDate(today);
      fetchCalendarData(today);
    }
  };

  return (
    <Grid container gap={SPACING.SMALL} direction="column" display={"flex"}>
      <Grid container gap={SPACING.SMALL} direction={"column"}>
        <Grid minWidth={210}>
          <Autocomplete
            disablePortal
            id="combo-box-demo"
            getOptionDisabled={(option) => option.disabled}
            options={
              buterData
                ? buterData.map((i) => ({
                    id: i?.key,
                    label: `${i?.fullname} (${i.mobile}) / استان ${i.province} / شهر ${i.city}`,
                    item: i,
                  }))
                : []
            }
            onChange={(event, value) => {
              setBuyerSelected(value?.id);
            }}
            renderInput={(params) => (
              <TextField {...params} label="انتخاب خریدار" />
            )}
          />
        </Grid>

        {buyerSelected && (
          <>
            <Grid xs={12} container>
              <Autocomplete
                fullWidth
                style={{ minWidth: 210 }}
                disablePortal
                id="hatching"
                options={
                  Array.isArray(productData) && productData.length > 0
                    ? productData.map((i) => {
                        return {
                          data: i,
                          label: `${i.name || ""}`,
                        };
                      })
                    : []
                }
                onChange={(event, value) => {
                  setProductKey(value?.data || null);
                }}
                renderInput={(params) => (
                  <TextField fullWidth {...params} label="انتخاب محصول" />
                )}
              />
            </Grid>

            <Formik
              innerRef={formikRef}
              initialValues={{
                weight_of_carcasses: "",
                clearance_code: "",
                date: moment(new Date()).format("YYYY-MM-DD"),
                production_date: "",
              }}
              validationSchema={validationSchema(selectedDateAmount)}
              onSubmit={(values) => {
                dispatch(
                  stewardSellOuutSubmitSell({
                    buyer_key: buyerSelected,
                    role_key: selectedSubUser?.key,
                    number_of_carcasses:
                      Math.round(
                        values?.weight_of_carcasses / productKey?.weightAverage
                      ) || 0,
                    weight_of_carcasses: parseInt(values.weight_of_carcasses),
                    date: values.date,
                    clearance_code: values.clearance_code,
                    product_key: productKey?.key,
                    sale_type: selectedInventory,
                    quota: approvedStatus,
                    production_date: values.production_date,
                    distribution_type: "web",
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    if (isInventory) {
                      fetchItems();
                    } else {
                      updateTable();
                    }
                    dispatch(fetchStewardBroadcastAndProducts());
                    dispatch(
                      DRAWER({ right: false, bottom: false, content: null })
                    );
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              {({ values, errors, touched, setFieldValue }) => (
                <Form>
                  <Grid container gap={SPACING.SMALL} direction={"column"}>
                    <Grid item>
                      <TextField
                        disabled
                        label="حجم تقریبی"
                        value={
                          Math.round(
                            values?.weight_of_carcasses /
                              productKey?.weightAverage
                          ) || 0
                        }
                        InputProps={{
                          readOnly: true,
                        }}
                      />
                    </Grid>
                    <LabelField label="نوع انبار">
                      <FormControl fullWidth>
                        <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>
                    <Grid xs={12}>
                      <DatePicker
                        label="تاریخ"
                        disabled={approvedStatus === "governmental"}
                        value={moment(values.date)}
                        onChange={(newValue) => {
                          const formatted =
                            moment(newValue).format("YYYY-MM-DD");
                          setFieldValue("date", formatted);
                          setSelectedFormDate(formatted);
                          fetchCalendarData(formatted);
                        }}
                        renderInput={(params) => (
                          <TextField
                            fullWidth
                            {...params}
                            size="small"
                            error={touched.date && Boolean(errors.date)}
                            helperText={touched.date && errors.date}
                          />
                        )}
                      />
                    </Grid>
                    <Grid item>
                      <Field
                        name="clearance_code"
                        as={TextField}
                        label="کد قرنطینه"
                        fullWidth
                        onChange={(e) =>
                          setFieldValue(
                            "clearance_code",
                            e.target.value.toUpperCase()
                          )
                        }
                        error={
                          touched.clearance_code &&
                          Boolean(errors.clearance_code)
                        }
                        helperText={
                          touched.clearance_code && errors.clearance_code
                        }
                      />
                    </Grid>

                    {/* <LabelField label="نوع قیمت">
                      <FormControl fullWidth>
                        <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> */}

                    <Grid
                      container
                      xs={12}
                      justifyContent="center"
                      alignItems="center"
                      gap={SPACING.TINY}
                      sx={{ width: "100%" }}
                    >
                      <MonthlyDataCalendar
                        onDateSelect={handleDateSelect}
                        dayData={calendarDayData}
                        selectedDate={selectedCalendarDate}
                        maxGregorianDate={values.date}
                        label={`تاریخ تولید گوشت ${
                          selectedDateAmount !== null
                            ? `(موجودی: ${selectedDateAmount?.toLocaleString()} کیلوگرم)`
                            : ""
                        }`}
                      />
                      {calendarDateError && (
                        <TextField
                          error
                          helperText={calendarDateError}
                          sx={{
                            visibility: "hidden",
                            height: 0,
                            mt: 0,
                            mb: 0,
                          }}
                        />
                      )}
                    </Grid>

                    <Grid item>
                      <Field
                        name="weight_of_carcasses"
                        as={TextField}
                        label="وزن لاشه‌ها"
                        fullWidth
                        disabled={!selectedDateAmount && !productionDate}
                        error={
                          !selectedDateAmount && !productionDate
                            ? true
                            : touched.weight_of_carcasses &&
                              Boolean(errors.weight_of_carcasses)
                        }
                        helperText={
                          !selectedDateAmount && !productionDate
                            ? "لطفاً ابتدا تاریخ تولید را انتخاب کنید!"
                            : touched.weight_of_carcasses &&
                              errors.weight_of_carcasses
                        }
                      />
                    </Grid>
                    <Grid item>
                      <Button
                        fullWidth
                        type="submit"
                        variant="contained"
                        disabled={!productKey || !productionDate}
                      >
                        ارسال
                      </Button>
                    </Grid>
                  </Grid>
                </Form>
              )}
            </Formik>
          </>
        )}
      </Grid>
    </Grid>
  );
};
