import React, {
  useContext,
  useEffect,
  useState,
  useCallback,
  useRef,
} from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  Autocomplete,
  Button,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import {
  slaughterSellCarcassOutProvinceGetBuyers,
  slaughterSellCarcassOutProvinceSubmitSell,
} from "../../services/slaughter-sell-carcass-out-province-get-buyers";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
import { AppContext } from "../../../../contexts/AppContext";
import moment from "moment";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { slaughterGetProductsService } from "../../services/slaughter-inventory-gets";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { DatePicker } from "@mui/x-date-pickers";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-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 { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

const getValidationSchema = (selectedDateAmount, productionDate) =>
  Yup.object({
    weight_of_carcasses: Yup.number()
      .required("وزن لاشه‌ها الزامی است")
      .integer("عدد باید صحیح باشد!")
      .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("تاریخ الزامی است")
      .test(
        "date-not-before-production",
        "تاریخ نمی‌تواند قبل از تاریخ تولید باشد",
        function (value) {
          if (!productionDate || !value) return true;
          return moment(value).isSameOrAfter(moment(productionDate), "day");
        }
      ),
  });

export const SlaughterSellCarcassOutProvinceSellSubmitSell = ({
  updateTable,
  fetchItems,
  isInventory,
}) => {
  const [buterData, setBuyerData] = useState([]);
  const [buyerSelected, setBuyerSelected] = useState(null);
  const [selectedInventory] = useState("free");
  const [approvedStatus, setApprovedStatus] = useState("governmental");
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);

  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 { selectedSubUser } = useSelector((state) => state.userSlice);
  const formikRef = useRef(null);

  useEffect(() => {
    dispatch(slaughterSellCarcassOutProvinceGetBuyers()).then((r) => {
      setBuyerData(r.payload.data);
    });
  }, [dispatch]);

  const [productData, setProductData] = useState([]);
  const [productKey, setProductKey] = useState(null);

  useEffect(() => {
    dispatch(
      slaughterGetProductsService({
        role_key: checkPathStartsWith("slaughter")
          ? 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, selectedSubUser]);

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

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

    // When governmental is selected, set date to today and disable DatePicker
    if (newType === "governmental" && formikRef.current) {
      const today = moment(new Date()).format("YYYY-MM-DD");
      formikRef.current.setFieldValue("date", today);
      setSelectedFormDate(today);
      fetchCalendarData(today);
    }
  };

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

      const data = calendarDayData[dateInfo.formattedDate];

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

      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, // 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("/kill-house-remain-weight/", {
          params: {
            date: dateParam,
            role: getRoleFromUrl(),
            role_key: checkPathStartsWith("slaughter")
              ? 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, selectedFormDate, selectedSubUser]
  );

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

  // When governmental is selected, set date to today
  useEffect(() => {
    if (approvedStatus === "governmental" && formikRef.current) {
      const today = moment(new Date()).format("YYYY-MM-DD");
      formikRef.current.setFieldValue("date", today);
      setSelectedFormDate(today);
      fetchCalendarData(today);
    }
  }, [approvedStatus, fetchCalendarData]);

  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]);

  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
                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"),
              }}
              validationSchema={getValidationSchema(
                selectedDateAmount,
                productionDate
              )}
              onSubmit={(values) => {
                dispatch(
                  slaughterSellCarcassOutProvinceSubmitSell({
                    buyer_key: buyerSelected,
                    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: productionDate,
                    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(
                      fetchSlaughterBroadcastAndProducts({
                        role_key: selectedSubUser?.key || "",
                      })
                    );
                    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>
                      <DatePicker
                        label="تاریخ"
                        disabled={approvedStatus === "governmental"}
                        value={moment(values.date)}
                        onChange={(newValue) => {
                          const formatted =
                            moment(newValue).format("YYYY-MM-DD");
                          setFieldValue("date", formatted);
                          // Keep a mirrored local state to drive calendar fetches
                          setSelectedFormDate(formatted);
                          fetchCalendarData(formatted);
                        }}
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            fullWidth
                            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%" }}
                      direction="column"
                    >
                      <MonthlyDataCalendar
                        onDateSelect={handleDateSelect}
                        dayData={calendarDayData}
                        selectedDate={selectedCalendarDate}
                        maxGregorianDate={values.date}
                        label={`تاریخ تولید گوشت ${
                          selectedDateAmount !== null
                            ? `(موجودی: ${selectedDateAmount?.toLocaleString()} کیلوگرم)`
                            : ""
                        }`}
                      />
                      {productionDate &&
                        values.date &&
                        moment(productionDate).isAfter(
                          moment(values.date),
                          "day"
                        ) && (
                          <Typography
                            sx={{
                              color: "#d32f2f",
                              fontSize: "0.75rem",
                              marginTop: "4px",
                              marginRight: "14px",
                              textAlign: "right",
                            }}
                          >
                            تاریخ تولید نمی‌تواند بعد از تاریخ انتخابی باشد
                          </Typography>
                        )}
                    </Grid>
                    <Grid item>
                      <Field name="weight_of_carcasses">
                        {({ field, form, meta }) => (
                          <NumberInput
                            allowLeadingZeros
                            thousandSeparator=","
                            decimalScale={0}
                            allowNegative={false}
                            fullWidth
                            id="weight_of_carcasses"
                            label="وزن لاشه‌ها"
                            variant="outlined"
                            value={field.value}
                            error={
                              (meta.touched && Boolean(meta.error)) ||
                              (selectedDateAmount &&
                                field.value > selectedDateAmount)
                            }
                            onChange={(e) => {
                              const value = e.target.value;
                              if (
                                value === "" ||
                                value === null ||
                                value === undefined
                              ) {
                                form.setFieldValue("weight_of_carcasses", "");
                                return;
                              }
                              const intValue = Math.floor(Number(value));
                              if (intValue > 0) {
                                form.setFieldValue(
                                  "weight_of_carcasses",
                                  intValue
                                );
                              } else if (intValue === 0) {
                                form.setFieldValue("weight_of_carcasses", "");
                              }
                            }}
                            onBlur={field.onBlur}
                            helperText={
                              selectedDateAmount &&
                              field.value > selectedDateAmount
                                ? `وزن نمی‌تواند بیشتر از موجودی تاریخ تولید (${selectedDateAmount?.toLocaleString()} کیلوگرم) باشد!`
                                : meta.touched && meta.error
                            }
                          />
                        )}
                      </Field>
                    </Grid>
                    <Grid container spacing={SPACING.SMALL}>
                      <Grid xs={6}>
                        <Button
                          fullWidth
                          type="submit"
                          variant="contained"
                          disabled={
                            !productKey ||
                            !productionDate ||
                            (selectedDateAmount &&
                              values.weight_of_carcasses >
                                selectedDateAmount) ||
                            (productionDate &&
                              values.date &&
                              moment(values.date).isBefore(
                                moment(productionDate),
                                "day"
                              ))
                          }
                        >
                          ثبت
                        </Button>
                      </Grid>
                      <Grid xs={6}>
                        <Button
                          fullWidth
                          variant="outlined"
                          color="primary"
                          onClick={() => {
                            dispatch(
                              DRAWER({
                                right: false,
                                bottom: false,
                                content: null,
                              })
                            );
                          }}
                        >
                          انصراف
                        </Button>
                      </Grid>
                    </Grid>
                  </Grid>
                </Form>
              )}
            </Formik>
          </>
        )}
      </Grid>
    </Grid>
  );
};
