import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { format } from "date-fns-jalali";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { AggregateUploadDoc } from "../aggregate-upload-doc/aggregate-upload-doc";
import ShowImage from "../../../../components/show-image/ShowImage";
import { useFormik } from "formik";
import { salughterAggregateQuantityService } from "../../services/salughter-aggregate-quantity";
import { useDispatch, useSelector } from "react-redux";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import { RiFileExcel2Fill } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { slaughterEnterLoadInformationGetDashboard } from "../../services/slaughter-enter-load-information-get-dashboard";
import { RiSearchLine } from "react-icons/ri";
import EditIcon from "@mui/icons-material/Edit";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import { provincePolicyGetWeightRange } from "../../../province/services/province-policy-get-weight-range";
import { isValidIndexWeight } from "../../../../utils/isValidIndexWeight";

export const EnterAggregateLoadInformation = () => {
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);

  const dispatch = useDispatch();

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `kill_house_request_aggregate_load/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);

    dispatch(LOADING_END());
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPage(1);
    setPerPage(perRows, fetchApiData(1));
  };

  // const updateTable = () => {
  //   fetchApiData(page !== 0 ? page : 1);
  // };

  useEffect(() => {
    fetchApiData(1);
  }, []);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `kill_house_request_aggregate_load/?check&role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  useEffect(() => {
    fetchApiData(1);
  }, [selectedDate1, selectedDate2, perPage]);

  const [dashboardData, setDashboardData] = useState([]);

  useEffect(() => {
    dispatch(
      slaughterEnterLoadInformationGetDashboard({
        selectedDate1,
        selectedDate2,
        text: textValue,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [selectedDate1, selectedDate2]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.assignmentInfo?.realQuantity ? (
          <Grid container direction="column">
            <Grid>
              {item?.assignmentInfo?.realQuantity?.toLocaleString()} قطعه
            </Grid>
            <Grid>
              {item?.assignmentInfo?.netWeight?.toLocaleString()} کیلوگرم
            </Grid>
            <Tooltip title="ویرایش اطلاعات بار" placement="top">
              <IconButton
                key={item.key}
                color="primary"
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت اطلاعات بار",
                      content: (
                        <Operation
                          item={item}
                          selectedDate={selectedDate1}
                          fetchApiData={fetchApiData}
                        />
                      ),
                    })
                  );
                }}
                size="small"
              >
                <EditIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          </Grid>
        ) : (
          <Tooltip title="ثبت اطلاعات بار" placement="top">
            <IconButton
              key={item.key}
              color="primary"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "ثبت اطلاعات بار",
                    content: (
                      <Operation
                        item={item}
                        selectedDate={selectedDate1}
                        fetchApiData={fetchApiData}
                      />
                    ),
                  })
                );
              }}
              size="small"
            >
              <AddCircleOutlineIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        ),
        <>
          {item?.assingmentInformation?.carWeightWithLoadImage ? (
            <Grid>
              <ShowImage
                src={item?.assingmentInformation?.carWeightWithLoadImage}
              />

              <AggregateUploadDoc
                key={item.key}
                isSingular
                item={item}
                updateTable={fetchApiData}
              />
            </Grid>
          ) : (
            <AggregateUploadDoc
              key={item.key}
              isSingular
              item={item}
              updateTable={fetchApiData}
            />
          )}
        </>,
        <ShowImage key={i} src={item?.assignmentInfo?.imageWithoutBar} />,
        <ShowImage key={i} src={item?.assignmentInfo?.imageWithBar} />,
        <Typography
          key={i}
          style={{ fontSize: "13px", color: item?.trash ? "red" : "black" }}
        >
          {item.barCode}
        </Typography>,
        <>
          <VetFarmEditTrafficCode
            updateTable={fetchApiData}
            killHouseRequestKey={item.key}
            trafficCode={item?.trafficCode}
            isEditable={
              getRoleFromUrl() === "ProvinceOperator" ||
              getRoleFromUrl() === "SuperAdmin" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "Supporter" ||
              getRoleFromUrl() === "VetSupervisor" ||
              (item.trash !== true &&
                item.assignmentStateArchive === "pending" &&
                !item?.clearanceCode &&
                (getRoleFromUrl() === "VetFarm" ||
                  getRoleFromUrl() === "CityVet"))
            }
          />
        </>,
        item?.amount?.toLocaleString() + " ﷼",
        item?.poultryRequest.sendDate
          ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd")
          : "-",
        `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`,
        item?.killer
          ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})`
          : "-",
        `${item.poultryRequest?.poultry?.unitName} (${item.poultryRequest.poultry?.user?.mobile})`,
        item?.poultryRequest?.age,
        item.quantity?.toLocaleString(),
        item?.weightInfo?.weight?.toLocaleString(),
        item?.poultryRequest?.amount?.toLocaleString() + " ﷼",
        item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼",
        `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`,
        `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`,
        item.vetAcceptedRealQuantity?.toLocaleString(),
        item.vetAcceptedRealWeight?.toLocaleString(),
        item?.poultryRequest.orderCode,
        item?.finalBarState,

        item?.poultryRequest?.freezing
          ? "انجماد"
          : item?.poultryRequest?.export
          ? "صادرات"
          : "عادی",
      ];
    });

    setTableData(d);
  }, [data]);

  return (
    <Grid container justifyContent="center">
      <Grid
        container
        alignItems="start"
        justifyContent="space-between"
        gap={2}
        paddingTop={2}
        mb={1}
      >
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <Grid>
            <DatePicker
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
          {!!data?.length && (
            <Grid>
              <Tooltip title="خروجی اکسل">
                <a
                  href={`${
                    axios.defaults.baseURL
                  }bar_excel/?start=${selectedDate1}&end=${selectedDate2}&role=${getRoleFromUrl()}&state=bar_pending&key=${userKey}&search=filter&value=${textValue}`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          )}
        </Grid>
      </Grid>
      <Grid container mt={2} mb={4} isDashboard>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد بار",
            "مجموع تعداد اولیه",
            "مجموع وزن اولیه (کیلوگرم)",
            "مجموع تعداد تحویلی دامپزشک",
            "مجموع وزن تحویلی دامپزشک (کیلوگرم)",
          ]}
          data={[
            [
              dashboardData?.lenKillHouseRequest?.toLocaleString(),
              dashboardData?.firstQuantity?.toLocaleString(),
              dashboardData?.firstWeight?.toLocaleString(),
              dashboardData?.vetAcceptedRealQuantity?.toLocaleString(),
              dashboardData?.vetAcceptedRealWeight?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "تعداد/وزن خالص",
          "سند",
          "بارنامه خالی",
          "بارنامه پر",
          "کدبار",
          "کد بهداشتی حمل و نقل",
          "قیمت مرغ زنده‌ی بار",
          "تاریخ کشتار",
          "خریدار",
          "کشتارکن اختصاصی",
          "مرغدار",
          "سن مرغ",
          "تعداد اولیه",
          "وزن اولیه بار (کیلوگرم)",
          "قیمت مرغدار",
          "قیمت کشتارگاه",
          "ماشین",
          "راننده",
          "تحویلی دامپزشک (قطعه)",
          "وزن تحویلی دامپزشک (کیلوگرم)",
          "کدسفارش کشتار",
          "وضعیت بار",
          "نوع کشتار",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="وارد کردن اطلاعات بار"
      />
    </Grid>
  );
};

const Operation = ({ item, fetchApiData }) => {
  const [openNotif] = useContext(AppContext);
  const { weightRange } = useSelector((state) => state.provinceSlice);
  useEffect(() => {
    dispatch(provincePolicyGetWeightRange());
  }, []);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      quantity: "",
      weight: "",
    },
    onSubmit: (values) => {
      // Handle form submission
      if (
        (item?.killhouseUser?.maximumLoadVolumeReduction !== 0 &&
          formik.values.quantity <
            item?.acceptedRealQuantity *
              (1 - item?.killhouseUser?.maximumLoadVolumeReduction / 100)) ||
        (item?.killhouseUser?.maximumLoadVolumeIncrease !== 0 &&
          formik.values.quantity >
            item?.acceptedRealQuantity *
              (1 + item?.killhouseUser?.maximumLoadVolumeIncrease / 100))
      ) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "حجم وارد شده با مجوز حداکثر افزایش/کاهش ورود اطلاعات بار مطابقت ندارد!",
          severity: "error",
        });
      } else if (
        getRoleFromUrl() !== "SuperAdmin" &&
        getRoleFromUrl() !== "AdminX" &&
        !isValidIndexWeight(
          weightRange,
          item?.poultryRequest?.age,
          parseInt(formik.values.weight) / parseInt(formik.values.quantity)
        )
      ) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "میانگین وزنی با احراز سنی مطابقت ندارد. لطفا با اتحادیه تماس بگیرید.",
          severity: "error",
        });
      } else {
        dispatch(
          salughterAggregateQuantityService({
            kill_house_request_key: item.key,
            role: getRoleFromUrl(),
            net_weight: values.weight,
            exploited_carcass: 0,
            real_quantity: values.quantity,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            dispatch(CLOSE_MODAL());
            fetchApiData(1);
          }
        });
      }
    },
    validate: (values) => {
      const errors = {};
      if (!/^\d+$/.test(values.weight)) {
        errors.weight = "لطفا عدد وارد کنید";
      }
      if (!/^\d+$/.test(values.quantity)) {
        errors.quantity = "لطفا عدد وارد کنید";
      }
      return errors;
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid
        container
        gap={SPACING.SMALL}
        alignItems="center"
        justifyContent="center"
      >
        <TextField
          label="وزن خالص (کیلوگرم)"
          variant="outlined"
          fullWidth
          type="text"
          name="weight"
          id="weight"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.weight}
          error={formik.touched.weight && Boolean(formik.errors.weight)}
          helperText={formik.touched.weight && formik.errors.weight}
        />
        <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}
        />

        <Button type="submit" fullWidth variant="contained">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
