import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { auctionGetAuctions } from "../../services/auction-get-auctions";
import { Button, ButtonGroup, Typography } from "@mui/material";
import { AuctionFilterRequestDate } from "../auction-filter-request-date/AuctionFilterRequestDate";
import { AuctionFilterRequestAdvance } from "../auction-filter-request-advance/AuctionFilterRequestAdvance";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getAuctionItemForTable } from "../../utils/get-auction-item-for-table";
import { format } from "date-fns-jalali";
import { AuctionFilterRequestZone } from "../auction-filter-request-zone/AuctionFilterRequestZone";
import {
  auctionFilterByAge,
  auctionFilterByCity,
  auctionFilterByDate,
  auctionFilterByPrice,
  auctionFilterByProvince,
  auctionFilterByQuantity,
  auctionFilterByRace,
  auctionFilterByWeight,
} from "../../../../lib/redux/slices/auctionSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const AuctionsView = () => {
  const dispatch = useDispatch();
  const { auctions } = useSelector((state) => state.auctionSlice || {});
  const { filterByDate } = useSelector((state) => state.auctionSlice || {});
  const { filterByCity } = useSelector((state) => state.auctionSlice || {});
  const { filterByProvince } = useSelector((state) => state.auctionSlice || {});
  const {
    filterByQuantity,
    filterByAge,
    filterByRace,
    filterByWeight,
    filterByPrice,
  } = useSelector((state) => state.auctionSlice || {});
  const [tableRows, setTableRows] = useState([]);
  const [minQuantity, setMinQuantity] = useState(0);
  const [maxQuantity, setMaxQuantity] = useState(0);

  // useEffect(() => {
  //   setInterval(() => {
  //     dispatch(auctionGetAuctions());
  //   }, 60000);
  // }, []);

  useEffect(() => {
    dispatch(auctionGetAuctions());
  }, [
    filterByDate,
    filterByCity,
    filterByQuantity,
    filterByPrice,
    filterByWeight,
    filterByAge,
    filterByRace,
  ]);
  useEffect(() => {
    if (auctions && Array.isArray(auctions) && auctions.length > 0) {
      const quantities = auctions
        .map((object) => object?.quantity)
        .filter((qty) => qty !== undefined && qty !== null);
      if (quantities.length > 0) {
        setMinQuantity(Math.min(...quantities));
        setMaxQuantity(Math.max(...quantities));
      }
    }
  }, [auctions]);

  useEffect(() => {
    if (auctions && Array.isArray(auctions)) {
      let data = [];
      const dateFilterCallback = (item) => {
        if (!filterByDate || !Array.isArray(filterByDate)) {
          return true;
        }
        if (!item?.sendDate) {
          return false;
        }
        try {
          const formattedDate = format(new Date(item.sendDate), "yyyy/MM/dd");
          return filterByDate.includes(formattedDate);
        } catch (error) {
          console.error("Error formatting date:", error);
          return false;
        }
      };
      const provinceCityFilterCallback = (item) => {
        if (filterByCity || filterByProvince) {
          if (filterByCity) {
            return item?.process?.city?.cityOperatorCity === filterByCity;
          } else if (filterByProvince) {
            return (
              item?.process?.city?.cityOperatorProvince === filterByProvince
            );
          }
        }
        return true;
      };
      const advanceFilterCallback = (item) => {
        if (filterByRace) {
          return item?.chickenBreed === filterByRace;
        }
        if (filterByQuantity && Array.isArray(filterByQuantity)) {
          const quantity = item?.quantity;
          if (quantity === undefined || quantity === null) {
            return false;
          }
          return (
            quantity >= (filterByQuantity[0] || 0) &&
            quantity <= (filterByQuantity[1] || Infinity)
          );
        }
        if (filterByPrice && Array.isArray(filterByPrice)) {
          if (item?.process?.killHouseAuctionsList) {
            const auctionsList = item.process.killHouseAuctionsList;
            if (Array.isArray(auctionsList) && auctionsList.length > 0) {
              const lastAuction = auctionsList[auctionsList.length - 1];
              const fee = lastAuction?.fee;
              if (fee === undefined || fee === null) {
                return false;
              }
              return (
                fee >= (filterByPrice[0] || 0) &&
                fee <= (filterByPrice[1] || Infinity)
              );
            }
          }
          return false;
        }
        if (filterByWeight && Array.isArray(filterByWeight)) {
          const weight = item?.IndexWeight;
          if (weight === undefined || weight === null) {
            return false;
          }
          return (
            weight >= (filterByWeight[0] || 0) &&
            weight <= (filterByWeight[1] || Infinity)
          );
        }
        if (filterByAge !== undefined && filterByAge !== null) {
          const age = item?.process?.poultry?.age;
          if (age === undefined || age === null) {
            return false;
          }
          return age <= filterByAge;
        }
        return true;
      };
      if (
        filterByDate ||
        filterByCity ||
        filterByProvince ||
        filterByQuantity ||
        filterByPrice ||
        filterByWeight ||
        filterByAge !== undefined ||
        filterByRace
      ) {
        data = auctions
          .filter(dateFilterCallback)
          .filter(provinceCityFilterCallback)
          .filter(advanceFilterCallback)
          .map((item, i) => {
            return getAuctionItemForTable(item, i, dispatch);
          });
      } else {
        data = auctions.map((item, i) => {
          return getAuctionItemForTable(item, i, dispatch);
        });
      }
      setTableRows(data);
    } else {
      setTableRows([]);
    }
  }, [
    auctions,
    filterByDate,
    filterByCity,
    filterByProvince,
    filterByQuantity,
    filterByPrice,
    filterByWeight,
    filterByAge,
    filterByRace,
    dispatch,
  ]);

  const columns =
    getRoleFromUrl() === "KillHouse"
      ? [
          "شماره مزایده",
          "کدسفارش",
          // "فروشنده",
          "قیمت کف",
          "قیمت سقف",
          "بالاترین قیمت پیشنهادی",
          "تعداد",
          "تاریخ درخواست کشتار",
          "نژاد و سن به روز",
          "وزن",
          "استان",
          "شهرستان",
          "زمان تا پایان",
          "عملیات",
        ]
      : [
          "شماره مزایده",
          "کدسفارش",
          // "فروشنده",
          "قیمت کف",
          "قیمت سقف",

          "بالاترین قیمت پیشنهادی",
          "تعداد",
          "تاریخ درخواست کشتار",
          "نژاد و سن به روز",
          "وزن",
          "استان",
          "شهرستان",
          "زمان تا پایان",
        ];

  return (
    <Grid container gap={SPACING.SMALL} p={SPACING.SMALL} width="100%">
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <Grid>
          <Typography color={(prop) => prop.palette.grey["A700"]}>
            فیلتر کردن مزایده ها
          </Typography>
        </Grid>
        <Grid>
          <ButtonGroup variant="text" aria-label="outlined button group">
            <Button
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: <AuctionFilterRequestDate />,
                    title: " فیلتر تاریخ",
                  })
                );
              }}
            >
              فیلتر تاریخ
            </Button>
            <Button
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: " فیلتر بر اساس شهر و استان",
                    content: <AuctionFilterRequestZone />,
                  })
                );
              }}
            >
              فیلتر استان و شهرستان
            </Button>
            <Button
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "فیلتر پیشرفته",
                    content: (
                      <AuctionFilterRequestAdvance
                        maxQuantity={maxQuantity}
                        minQuantity={minQuantity}
                      />
                    ),
                  })
                );
              }}
            >
              فیلتر پیشرفته
            </Button>
            <Button
              onClick={() => {
                dispatch(LOADING_START());
                dispatch(auctionFilterByDate(""));
                dispatch(auctionFilterByCity(""));
                dispatch(auctionFilterByProvince(""));
                dispatch(auctionFilterByQuantity(""));
                dispatch(auctionFilterByAge(""));
                dispatch(auctionFilterByRace(""));
                dispatch(auctionFilterByWeight(""));
                dispatch(auctionFilterByPrice(""));
                dispatch(auctionGetAuctions());
                dispatch(LOADING_END());
              }}
            >
              حذف همه فیلترها
            </Button>
          </ButtonGroup>
        </Grid>
      </Grid>
      <AdvancedTable
        name="مزایده های در حال انجام"
        columns={columns}
        data={tableRows}
      />
    </Grid>
  );
};
