import {
  Button,
  Collapse,
  IconButton,
  List,
  ListItem,
  ListItemText,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import axios from "axios";
import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import { AppContext } from "../../../contexts/AppContext";
import { guildGetInventoryStockService } from "../services/guild-get-inventory-stock";
import { guildGetStewards } from "../services/guild-get-stewards";
import { formatJustDate } from "../../../utils/formatTime";
import { SPACING } from "../../../data/spacing";
import { Grid } from "../../../components/grid/Grid";
import { SimpleTable } from "../../../components/simple-table/SimpleTable";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";

import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../lib/redux/slices/appSlice";
import { GuildAddSteward } from "./GuildAddSteward";
import { guildGetAllocationData } from "../services/guildGetAllocationData";
import { GuildManageInventoryAllocationOperations } from "./GuildManageInventoryAllocationOperations";
import { guildInventoryFinalSubmitService } from "../services/guildInventoryFinalSubmitService";
import BoxList from "../../../components/box-list/BoxList";
import { RespSlaughterGuildListItem } from "../../slaughter-house/components/resp-slaughter-guild-list-item/RespSlaughterGuildListItem";
import { RespGuildExclusiveItem } from "../../slaughter-house/components/resp-guild-exclusive-item/RespGuildExclusiveItem";
import { SlaughterSubmitOutProvinceSell } from "../../slaughter-house/components/slaughter-submit-out-province-sell/SlaughterSubmitOutProvinceSell";
import { guildGetFreeSaleBarService } from "../services/guild-get-free-sale-bar";
import { guildDeleteOutOfProvinceSell } from "../services/guild-delete-free-sale";

export const GuildBroadCastManagement = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1, setSelectedDate1] = useContext(AppContext);
  const [stewardsDataTable, setStewardsDataTable] = useState([]);
  const [inventoryAllocationsDataTable, setInventoryAllocationsDataTable] =
    useState([]);

  const {
    guildGetInventoryStock,
    guildStewards,
    guildGetGuildData,
    guildFreeSaleBars,
  } = useSelector((state) => state.generalSlice);

  const [outOfProvinceSells, setOutOfProvinceSells] = useState([]);

  useEffect(() => {
    dispatch(
      guildGetInventoryStockService({
        date: selectedDate1,
      })
    ).then(() => {
      dispatch(
        guildGetFreeSaleBarService({
          date: selectedDate1,
          steward_key: guildGetInventoryStock?.stewardKey,
        })
      );
    });
    dispatch(guildGetStewards({ date: selectedDate1 }));
    dispatch(
      guildGetAllocationData({
        date: selectedDate1,
      })
    );
  }, [selectedDate1]);

  useEffect(() => {
    const inventoryAllocationsData = guildGetGuildData?.map((item, i) => {
      let sellType, sellerType;
      if (item.sellerType === "guilds") {
        sellerType = "صنف";
      } else if (item.sellerType === "steward") {
        sellerType = "مباشر";
      }

      if (item.sellType === "free") {
        sellType = "آزاد";
      } else {
        if (item.type === "manual") {
          sellType = "اختصاصی (دستی)";
        } else {
          sellType = "اختصاصی (اتوماتیک)";
        }
      }

      return [
        i + 1,
        item?.guilds?.guildsId,
        formatJustDate(item.date),
        sellerType,
        sellType,
        item?.guilds?.guildsName,
        item?.guilds?.user?.fullname,
        item?.guilds?.user?.nationalId,
        item?.guilds?.user?.mobile,
        item?.guilds?.typeActivity,
        item?.guilds?.areaActivity,
        item?.guilds?.licenseNumber,
        item?.guilds?.address?.city.name,
        item?.numberOfCarcasses,
        item?.weightOfCarcasses,
        item?.loggedRegistrationCode ? item.loggedRegistrationCode : "-",
        <GuildManageInventoryAllocationOperations item={item} key={i} />,
      ];
    });
    setInventoryAllocationsDataTable(inventoryAllocationsData);

    const d1 = guildStewards?.map((item, i) => {
      return [
        item?.guildsId,
        "صنف",
        item.guildsName,
        item.user.fullname,
        item.user.nationalId,
        item.user.mobile,
        item.typeActivity,
        item.areaActivity,
        item.licenseNumber,
        item.address.city.name,
        item?.allocationLimit
          ? `${item?.allocationLimit?.toLocaleString()} کیلوگرم`
          : "بدون محدودیت",
        <Button
          key={i}
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "تخصیص به صنف",
                size: 300,
                content: (
                  <GuildAddSteward
                    sellType={"exclusive"}
                    key={item.key + i}
                    isGuild={false}
                    stewardKey={item.key}
                    totalAverageWeightOfCarcasses={
                      guildGetInventoryStock?.totalAverageWeightOfCarcasses
                    }
                  />
                ),
              })
            );
          }}
        >
          تخصیص
        </Button>,
      ];
    });

    setStewardsDataTable(d1);

    const sells = guildFreeSaleBars?.map((item, i) => {
      return [
        i + 1,
        formatJustDate(item?.createDate),
        item?.buyerName,
        item?.buyerMobile,
        item?.province,
        item?.city,
        item?.driverName,
        item?.driverMobile,
        item?.driverName,
        item?.clearanceCode,
        item?.numberOfCarcasses,
        item?.weightOfCarcasses,
        <>
          <IconButton
            key={i}
            aria-label="delete"
            color="primary"
            onClick={() => {
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  title: "ویرایش فروش خارج از استان",
                  content: (
                    <SlaughterSubmitOutProvinceSell
                      stewardKey={guildGetInventoryStock?.stewardKey}
                      isEdit={true}
                      item={item}
                      selectedDate={selectedDate1}
                    />
                  ),
                })
              );
            }}
          >
            <EditIcon />
          </IconButton>
          <IconButton
            key={i}
            aria-label="delete"
            color="secondary"
            onClick={() => {
              dispatch(guildDeleteOutOfProvinceSell(item?.key)).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  dispatch(
                    guildGetFreeSaleBarService({
                      date: selectedDate1,
                      steward_key: guildGetInventoryStock?.stewardKey,
                    })
                  );
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.data.result,
                    severity: "success",
                  });
                }
              });
            }}
          >
            <DeleteIcon />
          </IconButton>
        </>,
      ];
    });

    setOutOfProvinceSells(sells);
  }, [guildStewards, guildGetGuildData, guildFreeSaleBars]);

  const finalSubmitDisabled =
    (Array.isArray(guildGetGuildData) && !guildGetGuildData?.length) ||
    (Array.isArray(guildGetGuildData) &&
      guildGetGuildData[0]?.finalRegistration);

  const [inventoryDate, setInventoryDate] = useState(new Date(selectedDate1));

  useEffect(() => {
    const tempDate = new Date(inventoryDate);
    tempDate.setDate(new Date(selectedDate1).getDate() - 1);
    setInventoryDate(tempDate);
  }, [selectedDate1]);

  const [isMessageVisible, setMessageVisible] = useState(true);

  const toggleMessageVisibility = () => {
    setMessageVisible(!isMessageVisible);
  };

  const isMobile = window.innerWidth <= 600;

  const [value, setValue] = useState("");
  const [searchFilter, setSearchFilter] = useState([]);

  const handleChange = (event) => {
    setValue(event.target.value);
    const regex = new RegExp(value, "i");
    const d = stewardsDataTable.filter((item) => regex.test(item));
    setSearchFilter(d);
  };

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      alignItems="center"
      justifyContent="start"
      width="100%"
    >
      <Typography variant="h6">مدیریت پخش</Typography>

      <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 width="100%">
        {isMobile ? (
          <Grid p={SPACING.TINY}>
            <Grid container alignItems="center" justifyContent="space-between">
              <Grid container alignItems="center">
                <Typography>موجودی انبار</Typography>

                <Tooltip title="خروجی اکسل">
                  <a
                    href={`${
                      axios.defaults.baseURL
                    }Broadcast_management/?date=${selectedDate1}&kill_house_key=${"AAA"}`}
                    rel="noreferrer"
                  >
                    <Button color="success">
                      <RiFileExcel2Fill size={32} />
                    </Button>
                  </a>
                </Tooltip>
              </Grid>
              <Grid>
                <Button
                  variant="contained"
                  onClick={() => {
                    dispatch(
                      DRAWER({
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        title: "فروش آزاد",
                        content: (
                          <SlaughterSubmitOutProvinceSell
                            stewardKey={guildGetInventoryStock?.stewardKey}
                            selectedDate={selectedDate1}
                          />
                        ),
                      })
                    );
                  }}
                >
                  فروش آزاد
                </Button>
              </Grid>
            </Grid>
            <BoxList
              columns={[
                "حجم لاشه ها",
                "وزن لاشه ها (کیلوگرم)",
                // "تعداد تخصیصات",
                "حجم لاشه تخصیص داده شده",
                "وزن تخصیص داده شده (کیلوگرم)",
                "حجم لاشه قابل تخصیص",
                "وزن قابل تخصیص (کیلوگرم)",
                "وزن بار فروش آزاد (کیلوگرم)",
                "حجم بار فروش آزاد (قطعه)",
              ]}
              data={[
                [
                  guildGetInventoryStock?.realNumberOfCarcasses?.toLocaleString(),
                  guildGetInventoryStock?.realWeightOfCarcasses?.toLocaleString(),
                  guildGetInventoryStock?.allocatedTotalNumberOfCarcasses?.toLocaleString(),
                  guildGetInventoryStock?.allocatedTotalWeightOfCarcasses?.toLocaleString(),
                  guildGetInventoryStock?.remainTotalNumberOfCarcasses?.toLocaleString(),
                  guildGetInventoryStock?.remainTotalWeightOfCarcasses?.toLocaleString(),
                  guildGetInventoryStock?.freeSaleWeight?.toLocaleString(),
                  guildGetInventoryStock?.freeSaleQuantity?.toLocaleString(),
                ],
              ]}
            />
          </Grid>
        ) : (
          <SimpleTable
            name={
              <Grid
                container
                alignItems="center"
                justifyContent="space-between"
              >
                <Grid container alignItems="center">
                  <Typography>موجودی انبار</Typography>

                  <Tooltip title="خروجی اکسل">
                    <a
                      href={`${
                        axios.defaults.baseURL
                      }Broadcast_management/?date=${selectedDate1}&kill_house_key=${"AAA"}`}
                      rel="noreferrer"
                    >
                      <Button color="success">
                        <RiFileExcel2Fill size={32} />
                      </Button>
                    </a>
                  </Tooltip>
                </Grid>
                <Grid>
                  <Button
                    variant="contained"
                    onClick={() => {
                      dispatch(
                        DRAWER({
                          right: !(window.innerWidth <= 600),
                          bottom: window.innerWidth <= 600,
                          title: "فروش آزاد",
                          content: (
                            <SlaughterSubmitOutProvinceSell
                              stewardKey={guildGetInventoryStock?.stewardKey}
                              selectedDate={selectedDate1}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    فروش آزاد
                  </Button>
                </Grid>
              </Grid>
            }
            columns={[
              "حجم لاشه ها",
              "وزن لاشه ها (کیلوگرم)",
              // "تعداد تخصیصات",
              "حجم لاشه تخصیص داده شده",
              "وزن تخصیص داده شده (کیلوگرم)",
              "حجم لاشه قابل تخصیص",
              "وزن قابل تخصیص (کیلوگرم)",
              "وزن بار فروش آزاد (کیلوگرم)",
              "حجم بار فروش آزاد (قطعه)",
            ]}
            data={[
              [
                guildGetInventoryStock?.realNumberOfCarcasses?.toLocaleString(),
                guildGetInventoryStock?.realWeightOfCarcasses?.toLocaleString(),
                guildGetInventoryStock?.allocatedTotalNumberOfCarcasses?.toLocaleString(),
                guildGetInventoryStock?.allocatedTotalWeightOfCarcasses?.toLocaleString(),
                guildGetInventoryStock?.remainTotalNumberOfCarcasses?.toLocaleString(),
                guildGetInventoryStock?.remainTotalWeightOfCarcasses?.toLocaleString(),
                guildGetInventoryStock?.freeSaleWeight?.toLocaleString(),
                guildGetInventoryStock?.freeSaleQuantity?.toLocaleString(),
              ],
            ]}
          />
        )}
      </Grid>
      <Grid width="100%">
        <List>
          <ListItem
            sx={{ backgroundColor: "#dfe6e9", cursor: "pointer" }}
            onClick={toggleMessageVisibility}
          >
            <ListItemText primary={"صنف اختصاصی"} />
            <Button variant="text" onClick={toggleMessageVisibility}>
              {isMessageVisible ? <ExpandLessIcon /> : <ExpandMoreIcon />}
            </Button>
          </ListItem>

          <Collapse in={isMessageVisible}>
            <Grid mt={SPACING.TINY}>
              <TextField
                label="جستجو ..."
                variant="outlined"
                size="small"
                onChange={handleChange}
                fullWidth
              />
            </Grid>
            {isMobile ? (
              <RespSlaughterGuildListItem
                data={value ? searchFilter : stewardsDataTable}
              />
            ) : (
              <ListItem>
                <SimpleTable
                  columns={[
                    "شناسه صنف",
                    "ماهیت",
                    "نام واحد صنفی",
                    "نام شخص/شرکت",
                    "کدملی",
                    "موبایل",
                    "نوع فعالیت",
                    "حوزه فعالیت",
                    "شماره مجوز",
                    "شهرستان",
                    "میانگین سهم",
                    "عملیات",
                  ]}
                  data={value ? searchFilter : stewardsDataTable}
                />
              </ListItem>
            )}
          </Collapse>
        </List>
      </Grid>
      {isMobile ? (
        <>
          <Grid
            container
            alignItems="center"
            gap={SPACING.SMALL}
            justifyContent="space-between"
          >
            <Typography>مدیریت کل تخصیصات</Typography>
            <Grid container gap={SPACING.SMALL} alignItems="center">
              <Button
                // disabled={!guildGetGuildData?.length}
                variant="outlined"
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "تخصیص آزاد به صنف",
                      content: (
                        <GuildAddSteward
                          isGuild
                          sellType="free"
                          totalAverageWeightOfCarcasses={
                            guildStewards.totalAverageWeightOfCarcasses
                          }
                        />
                      ),
                    })
                  );
                }}
              >
                تخصیص آزاد به صنف
              </Button>
              <Button
                variant="contained"
                disabled={finalSubmitDisabled}
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت نهایی",
                      content: (
                        <Grid container gap={SPACING.SMALL}>
                          <Typography>
                            در صورت ثبت نهایی انجام هیچگونه عملیاتی مانند حذف و
                            ویرایش امکان پذیر نمی باشد.
                          </Typography>
                          <Grid
                            container
                            direction="column"
                            gap={SPACING.TINY}
                            width="100%"
                          >
                            <Button
                              fullWidth
                              variant="contained"
                              onClick={() => {
                                dispatch(
                                  guildInventoryFinalSubmitService({
                                    steward_guild_allocation_list:
                                      guildGetGuildData.map((item) => item.key),
                                  })
                                ).then((r) => {
                                  dispatch(CLOSE_MODAL());
                                  if (r.payload.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: r.payload.error,
                                      severity: "error",
                                    });
                                  } else {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "عملیات با موفقیت انجام شد.",
                                      severity: "success",
                                    });
                                  }
                                });
                              }}
                            >
                              تایید
                            </Button>
                            <Button
                              fullWidth
                              color="error"
                              variant="contained"
                              onClick={() => {
                                dispatch(CLOSE_MODAL());
                              }}
                            >
                              لغو
                            </Button>
                          </Grid>
                        </Grid>
                      ),
                    })
                  );
                }}
              >
                ارسال یکجا کداحراز
              </Button>
            </Grid>
          </Grid>
          <RespGuildExclusiveItem data={inventoryAllocationsDataTable} />
          {!!outOfProvinceSells?.length && (
            <Grid mt={2}>
              <BoxList
                name={"فروش خارج از استان"}
                columns={[
                  "ردیف",
                  "تاریخ",
                  "نام خریدار",
                  "تلفن",
                  "استان",
                  "شهر",
                  "نام راننده",
                  "تلفن راننده",
                  "نوع خودرو",
                  "کد قرنطینه",
                  "حجم لاشه",
                  "وزن لاشه",
                  "عملیات",
                ]}
                data={outOfProvinceSells}
              />
            </Grid>
          )}
        </>
      ) : (
        <Grid width="100%">
          <SimpleTable
            name={
              <Grid
                container
                alignItems="center"
                gap={SPACING.SMALL}
                justifyContent="space-between"
              >
                <Typography>مدیریت کل تخصیصات</Typography>
                <Grid container gap={SPACING.SMALL} alignItems="center">
                  <Button
                    // disabled={!guildGetGuildData?.length}
                    variant="outlined"
                    onClick={() => {
                      dispatch(
                        OPEN_MODAL({
                          title: "تخصیص آزاد به صنف",
                          content: (
                            <GuildAddSteward
                              isGuild
                              sellType="free"
                              totalAverageWeightOfCarcasses={
                                guildGetInventoryStock?.totalAverageWeightOfCarcasses
                              }
                            />
                          ),
                        })
                      );
                    }}
                  >
                    تخصیص آزاد به صنف
                  </Button>
                  <Button
                    variant="contained"
                    disabled={finalSubmitDisabled}
                    onClick={() => {
                      dispatch(
                        OPEN_MODAL({
                          title: "ثبت نهایی",
                          content: (
                            <Grid container gap={SPACING.SMALL}>
                              <Typography>
                                در صورت ثبت نهایی انجام هیچگونه عملیاتی مانند
                                حذف و ویرایش امکان پذیر نمی باشد.
                              </Typography>
                              <Grid
                                container
                                direction="column"
                                gap={SPACING.TINY}
                                width="100%"
                              >
                                <Button
                                  fullWidth
                                  variant="contained"
                                  onClick={() => {
                                    dispatch(
                                      guildInventoryFinalSubmitService({
                                        steward_guild_allocation_list:
                                          guildGetGuildData.map(
                                            (item) => item.key
                                          ),
                                      })
                                    ).then((r) => {
                                      dispatch(CLOSE_MODAL());
                                      if (r.payload.error) {
                                        openNotif({
                                          vertical: "top",
                                          horizontal: "center",
                                          msg: r.payload.error,
                                          severity: "error",
                                        });
                                      } else {
                                        openNotif({
                                          vertical: "top",
                                          horizontal: "center",
                                          msg: "عملیات با موفقیت انجام شد.",
                                          severity: "success",
                                        });
                                      }
                                    });
                                  }}
                                >
                                  تایید
                                </Button>
                                <Button
                                  fullWidth
                                  color="error"
                                  variant="contained"
                                  onClick={() => {
                                    dispatch(CLOSE_MODAL());
                                  }}
                                >
                                  لغو
                                </Button>
                              </Grid>
                            </Grid>
                          ),
                        })
                      );
                    }}
                  >
                    ارسال یکجا کداحراز
                  </Button>
                </Grid>
              </Grid>
            }
            columns={[
              "ردیف",
              "شناسه صنف",
              "تاریخ ثبت",
              "ماهیت",
              "نوع تخصیص",
              "نام واحد صنفی",
              "نام شخص/شرکت",
              "کدملی",
              "موبایل",
              "نوع فعالیت",
              "حوزه فعالیت",
              "شماره مجوز",
              "شهرستان",
              "حجم لاشه",
              "وزن لاشه",
              "کداحراز",
              "عملیات",
            ]}
            data={inventoryAllocationsDataTable}
          />
          {!!outOfProvinceSells?.length && (
            <Grid mt={2}>
              <SimpleTable
                name={"فروش خارج از استان"}
                columns={[
                  "ردیف",
                  "تاریخ",
                  "نام خریدار",
                  "تلفن",
                  "استان",
                  "شهر",
                  "نام راننده",
                  "تلفن راننده",
                  "نوع خودرو",
                  "کد قرنطینه",
                  "حجم لاشه",
                  "وزن لاشه",
                  "عملیات",
                ]}
                data={outOfProvinceSells}
              />
            </Grid>
          )}
        </Grid>
      )}
    </Grid>
  );
};
