import { Button, TextField, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../components/grid/Grid";
import { SimpleTable } from "../../../components/simple-table/SimpleTable";
import { AppContext } from "../../../contexts/AppContext";
import { SPACING } from "../../../data/spacing";
import { AdvancedTable } from "../../../components/advanced-table/AdvancedTable";
import { OPEN_MODAL } from "../../../lib/redux/slices/appSlice";
import { RegisterEditDeliveryNumberAndWeight } from "../../guild/components/RegisterEditDeliveryNumberAndWeight";
import { GuildReceiveBarOperation } from "../../guild/components/GuildReceiveBarOperation";
import { senfGetInventoryStockService } from "../../guild/services/senf-get-inventory-stock";
import { senfGetInventoryAllocatedService } from "../../guild/services/senf-get-inventory-allocated";
import { getFaUserRole } from "../../../utils/getFaUserRole";
import { formatJustDate } from "../../../utils/formatTime";

export const SenfStock = () => {
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState([]);
  const [, , selectedDate1, setSelectedDate1] = useContext(AppContext);
  const { senfGetInventoryStock, senfGetInventoryAllocated } = useSelector(
    (state) => state.generalSlice
  );

  useEffect(() => {
    dispatch(
      senfGetInventoryStockService({
        date: selectedDate1,
      })
    );
    dispatch(
      senfGetInventoryAllocatedService({
        date: selectedDate1,
      })
    );
  }, [selectedDate1]);

  useEffect(() => {
    if (senfGetInventoryAllocated?.length > 0) {
      const d = senfGetInventoryAllocated?.map((item, i) => {
        let state = "";
        if (item?.receiverState === "accepted") {
          state = "تحویل گرفته شده";
        } else if (item?.receiverState === "rejected") {
          state = "رد شده";
        } else {
          state = "در انتظار تحویل";
        }

        return [
          i + 1,
          `${getFaUserRole(item?.seller?.sellerRole)} - ${
            item?.seller?.sellerName
          } (${item?.seller?.sellerMobile})`,
          formatJustDate(item.createDate),
          item?.numberOfCarcasses?.toLocaleString() + " قطعه",
          item?.weightOfCarcasses?.toLocaleString() + " کیلوگرم",
          <Grid container direction="column" key={item.key}>
            {item?.receiverRealNumberOfCarcasses && (
              <>
                <Typography variant="caption">
                  {item?.receiverRealNumberOfCarcasses?.toLocaleString() +
                    " قطعه"}
                </Typography>
                <Typography variant="caption">
                  {item?.receiverRealWeightOfCarcasses?.toLocaleString() +
                    " کیلوگرم"}
                </Typography>
              </>
            )}
            {item?.receiverState === "pending" && (
              <Grid>
                <Button
                  onClick={() => {
                    dispatch(
                      OPEN_MODAL({
                        title: "ثبت/ویرایش تعداد و وزن تحویلی",
                        content: (
                          <RegisterEditDeliveryNumberAndWeight item={item} />
                        ),
                      })
                    );
                  }}
                >
                  {item?.receiverRealNumberOfCarcasses ? "ویرایش" : "ثبت"}
                </Button>
              </Grid>
            )}
          </Grid>,
          <Grid container direction="column" key={item.key} gap={SPACING.SMALL}>
            {item.receiverState === "pending" ? (
              <Button
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت تحویل بار",
                      content: <GuildReceiveBarOperation item={item} />,
                    })
                  );
                }}
              >
                تحویل بار
              </Button>
            ) : (
              state
            )}
          </Grid>,
        ];
      });

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

  return (
    <Grid container direction="column" gap={SPACING.SMALL}>
      <Grid>
        <SimpleTable
          name={
            <Grid
              container
              gap={SPACING.SMALL}
              alignItems="center"
              justifyContent="space-between"
            >
              <Grid container gap={SPACING.SMALL} alignItems="center">
                <Typography>موجودی انبار</Typography>
                <DatePicker
                  label="تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate1}
                  onChange={(e) => {
                    setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
            </Grid>
          }
          columns={[
            "تعداد بار تخصیصی",
            "وزن لاشه تخصیصی",
            "حجم لاشه تخصیصی",
            "وزن لاشه تحویلی",
            "حجم لاشه تحویلی",
          ]}
          data={[
            [
              senfGetInventoryStock?.barQuantity,
              senfGetInventoryStock?.weightOfCarcasses + " کیلوگرم",
              senfGetInventoryStock?.numberOfCarcasses + " قطعه",
              senfGetInventoryStock?.realWeightOfCarcasses + " کیلوگرم",
              senfGetInventoryStock?.realNumberOfCarcasses + " قطعه",
            ],
          ]}
        />
      </Grid>
      <Grid>
        <AdvancedTable
          name="بارهای اختصاصی"
          columns={[
            "ردیف",
            "فروشنده",
            "تاریخ تخصیص",
            "تعداد تخصیص",
            "وزن تخصیص",
            "تعداد/وزن واقعی تحویلی",
            "عملیات",
          ]}
          data={dataTable}
        />
      </Grid>
    </Grid>
  );
};
