import { Button, IconButton, TextField } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch, useSelector } from "react-redux";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
// import { AvicultureNewRequest } from "../aviculture-new-request/AvicultureNewRequest";
// import HelpOutlineIcon from "@mui/icons-material/HelpOutline";
import DeleteIcon from "@mui/icons-material/Delete";
import { AppContext } from "../../../../contexts/AppContext";
import { avicultureGetRequests } from "../../services/aviculture-requests";
import { archiveDeleteKillRequestService } from "../../services/aviculture-delete-kill-request";
import { formatJustDate } from "../../../../utils/formatTime";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { CityNewKillRequest } from "../../../city/components/city-new-kill-request/CityNewKillRequest";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const AvicultureActiveRequests = () => {
  const [dataTable, setDataTable] = useState([]);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const { avicultureRequests } = useSelector((state) => state.avicultureSlice);

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

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

  useEffect(() => {
    dispatch(avicultureGetRequests({ selectedDate1, selectedDate2 }));
  }, [selectedDate1, selectedDate2]);

  useEffect(() => {
    const filteredData =
      Array.isArray(avicultureRequests) &&
      avicultureRequests?.filter(
        (item) =>
          (item.stateProcess === "accepted" ||
            item.stateProcess === "pending") &&
          item.finalState !== "archive"
      );
    let d;
    if (filteredData) {
      d = filteredData?.map((item, i) => {
        let sellType = "";
        if (item.directBuying) {
          sellType = "خرید مستقیم";
        } else if (item.union) {
          sellType = "خرید خارج از استان";
        } else {
          sellType = "اتحادیه";
        }
        return [
          i + 1,
          item.orderCode,
          sellType,
          item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
          item?.directBuyingBuyerInfo
            ? `${item?.directBuyingBuyerInfo?.buyerFullname} (${item?.directBuyingBuyerInfo?.buyerMobile})`
            : "-",
          item.directBuyingKillPlace ? item.directBuyingKillPlace : "-",
          item?.createDate ? formatJustDate(item?.createDate) : "",
          item?.sendDate ? formatJustDate(item?.sendDate) : "",
          `${item.process?.poultry?.poultryName} (${item.process?.poultry?.poultryMobile})`,
          `${item.process?.poultry?.poultryProvince}/${item.process?.poultry?.poultryCity}`,
          formatJustDate(item.process?.poultryHatching?.date),
          item.process?.poultry?.age,
          item.IndexWeight,
          item.process?.poultry?.poultryQuantity.toLocaleString(),
          (
            item.IndexWeight * item.process?.poultry?.poultryQuantity
          ).toLocaleString(),

          <IconButton
            key={item?.orderCode}
            disabled={item?.directBuyingKillPlace}
            aria-label="delete"
            color="error"
            className="avicultureActiveRequestsBtn"
            onClick={() => {
              dispatch(
                archiveDeleteKillRequestService(
                  item?.process?.poultry?.poultryRequestId
                )
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  dispatch(avicultureGetRequests());
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            <DeleteIcon />
          </IconButton>,
        ];
      });
    }

    setDataTable(d);
  }, [avicultureRequests]);

  return (
    <>
      <Grid container gap={SPACING.MEDIUM} direction="column" xs={12}>
        <Grid
          container
          gap={SPACING.SMALL}
          justifyContent={{ xs: "center", lg: "space-between" }}
          alignSelf="center"
          alignItems="center"
          xs={12}
          direction={{ xs: "column", lg: "row" }}
          width="100%"
        >
          <Grid
            container
            gap={SPACING.SMALL}
            alignItems={"start"}
            direction={"column"}
            width="100%"
          >
            <Grid container width="100%" gap={SPACING.SMALL}>
              <Button
                className="avicultureNewRequestBtn"
                variant={"contained"}
                onClick={() => {
                  dispatch(
                    DRAWER({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      title: "ثبت درخواست کشتار",
                      content: <CityNewKillRequest isAviculture />,
                    })
                  );
                }}
              >
                ثبت درخواست کشتار
              </Button>

              {/* <Button
                onClick={() => setIsTourOpen(!isTourOpen)}
                variant="outlined"
                endIcon={<HelpOutlineIcon />}
              >
                راهنما
              </Button> */}
            </Grid>
            <Grid width="100%" className="avicultureActiveRequestsView">
              <Grid container alignItems="center" gap={SPACING.SMALL}>
                <Grid>
                  <DatePicker
                    label="از تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate1}
                    onChange={(e) => {
                      setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    label="تا تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
              </Grid>
              <ResponsiveTable
                title="درخواست های کشتار"
                columns={[
                  "ردیف",
                  "کد سفارش",
                  "نوع فروش",
                  "نوع کشتار",
                  "اطلاعات خریدار",
                  "محل کشتار",
                  "تاریخ ثبت درخواست",
                  "تاریخ کشتار",
                  "مرغدار (تلفن)",
                  "استان/شهر",
                  "تاریخ جوجه ریزی",
                  "سن مرغ",
                  "میانگین وزنی",
                  "تعداد",
                  "وزن بار (کیلوگرم)",
                  "حذف",
                ]}
                data={dataTable}
              />
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};
