import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Box,
  Button,
  FormControl,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { Grid } from "../../../../components/grid/Grid";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { formatJustDate } from "../../../../utils/formatTime";
import { slaughterGetInventoryStock } from "../../services/salughter-get-inventory-stock";
import { slaughterGetInventoryFreeBarsService } from "../../services/slaughter-get-inventory-free-bars";
import { slaughterInventoryBarsService } from "../../services/slaughter-inventory-bars";
import { SlaughterFreeBarsOperations } from "../slaughter-free-bars-operations/SlaughterFreeBarsOperations";
import { SlaughterSubmitFreeBar } from "../slaughter-submit-free-bar/SlaughterSubmitFreeBar";
import { setInventorySelectedKillHouse } from "../../../../lib/redux/slices/slaughterSlice";
import axios from "axios";
import { RiFileExcel2Fill } from "react-icons/ri";
import KeyboardDoubleArrowUpIcon from "@mui/icons-material/KeyboardDoubleArrowUp";
import KeyboardDoubleArrowDownIcon from "@mui/icons-material/KeyboardDoubleArrowDown";
import { SlaughterSubmitRealInventory } from "../slaughter-submit-real-inventory/SlaughterSubmitRealInventory";
import SettingsIcon from "@mui/icons-material/Settings";
import BoxList from "../../../../components/box-list/BoxList";
import { RespSlaughterStockBarSystem } from "../resp-slaughter-stock-bar-system/RespSlaughterStockBarSystem";
export const SlaughterStock = () => {
  const [expanded, setExpanded] = useState("panel1");

  const handleChange = (panel) => (event, isExpanded) => {
    setExpanded(isExpanded ? panel : false);
  };

  const dispatch = useDispatch();
  const [freeBarsDataTable, setFreeBarsDataTable] = useState([]);
  const [inventoryBarsDataTable, setInventoryBarsDataTable] = useState([]);
  const {
    slaughterGetInventoryStockData,
    inventorySelectedKillHouse,
    slaughterGetInventoryFreeBars,
    slaughterInventoryBars,
    profile,
  } = useSelector((state) => state.slaughterSlice);
  const [, , selectedDate1, setSelectedDate1] = useContext(AppContext);
  const handleChangeInventory = (event) => {
    dispatch(setInventorySelectedKillHouse(event.target.value));
  };

  const updateTable = () => {
    dispatch(
      slaughterGetInventoryStock({
        date: selectedDate1,
        kill_house_key: inventorySelectedKillHouse,
      })
    );
    dispatch(
      slaughterGetInventoryFreeBarsService({
        selectedDate1,
        kill_house_key: inventorySelectedKillHouse,
      })
    );
    dispatch(
      slaughterInventoryBarsService({
        selectedDate1,
        kill_house_key: inventorySelectedKillHouse,
      })
    );
  };

  useEffect(() => {
    updateTable();
  }, [selectedDate1, inventorySelectedKillHouse]);

  useEffect(() => {
    const d = slaughterGetInventoryFreeBars?.map((item) => {
      return [
        item.poultryName,
        item.buyType === "live" ? "مرغ زنده" : "کشتار شده",
        `${item.province}/${item.city}`,
        formatJustDate(item.date),
        item.vetFarmName
          ? `${item.vetFarmName} (${item.vetFarmMobile})`
          : "ندارد",
        item.car,
        `${item.driverName} (${item.driverMobile})`,
        item.barClearanceCode,
        item.quantity.toLocaleString(),
        item.liveWeight.toLocaleString(),
        item.numberOfCarcasses.toLocaleString(),
        item.weightOfCarcasses.toLocaleString(),
        <a href={item.barImage} key={item.key}>
          <img src={item.barImage} width="50" height="50" alt="doc" />
        </a>,

        <SlaughterFreeBarsOperations
          key={item.key}
          item={item}
          inventoryKey={slaughterGetInventoryStockData?.key}
        />,
      ];
    });
    setFreeBarsDataTable(d);
  }, [slaughterGetInventoryFreeBars]);

  useEffect(() => {
    const d = slaughterInventoryBars?.map((item, i) => {
      let state = "";
      if (item.assignmentState === "no_state") {
        state = "وارد کردن اطلاعات بار";
      } else if (item.assignmentState === "accepted") {
        state = "تایید نهایی";
      } else if (item.assignmentState === "pending") {
        state = "در انتظار تایید تخلیه";
      }
      // const assignmentRealQuantity =
      //   item.assignmentState === "rejected"
      //     ? "-"
      //     : item.assignmentRealQuantity?.toLocaleString();

      return [
        item.barCode,
        item.poultryName,
        item.killHouseName,
        item.poultryReqOrderCode,
        item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
        item.poultryCity,
        formatJustDate(item.date),
        item.chickenBreed,
        item.vetName ? `${item.vetName} (${item.vetMobile})` : "ندارد",
        item.killHouseVetName
          ? `${item.killHouseVetName} (${item.killHouseVetMobile})`
          : "ندارد",
        `${item.driverName}/${item.typeCar}`,
        item.trafficCode,
        item.barClearanceCode ? item.barClearanceCode : "-",
        item?.assignmentRealQuantity?.toLocaleString(),
        item?.assignmentNetWeight?.toLocaleString(),
        state,
        item?.wareHouseAcceptedRealQuantity.toLocaleString(),
        item?.wareHouseAcceptedRealWeight.toLocaleString(),
        item?.weightLoss + "%",
        <Tooltip title="ورود بار به انبار" key={i}>
          <IconButton
            // disabled={
            //   item?.wareHouseAcceptedRealQuantity ||
            //   item?.wareHouseAcceptedRealWeight
            // }
            size={"small"}
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ثبت موجودی واقعی",
                  content: (
                    <SlaughterSubmitRealInventory
                      item={item}
                      inventorySelectedKillHouse={inventorySelectedKillHouse}
                    />
                  ),
                })
              );
            }}
          >
            <SettingsIcon fontSize="small" />
          </IconButton>
        </Tooltip>,
      ];
    });
    setInventoryBarsDataTable(d);
  }, [slaughterInventoryBars]);

  const invenotryStockData = () => {
    let data = [];
    if (
      slaughterGetInventoryStockData?.updatedWeightOfCarcasses ||
      slaughterGetInventoryStockData?.updatedNumberOfCarcasses
    ) {
      data = [
        [
          "سیستمی:",
          slaughterGetInventoryStockData?.barQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.allocatedQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.barLiveWeight.toLocaleString(),
          slaughterGetInventoryStockData?.numberOfCarcasses.toLocaleString(),
          Number(
            slaughterGetInventoryStockData?.weightOfCarcasses.toFixed(0)
          ).toLocaleString(),
          slaughterGetInventoryStockData?.aveWeightOfCarcasses.toFixed(2),
          slaughterGetInventoryStockData?.freeBarQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.numberOfFreeCarcasses.toLocaleString(),
          slaughterGetInventoryStockData?.freeWeightOfCarcasses.toLocaleString(),
          slaughterGetInventoryStockData?.totalBarQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.totalNumberOfCarcasses.toLocaleString(),
          slaughterGetInventoryStockData?.totalWeightOfCarcasses.toLocaleString(),
        ],
        [
          "ویرایش:",
          slaughterGetInventoryStockData?.barQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.allocatedQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.barLiveWeight.toLocaleString(),
          <Grid
            container
            alignItems="center"
            justifyContent="center"
            key={"eee"}
          >
            {slaughterGetInventoryStockData?.updatedNumberOfCarcasses.toLocaleString()}
            {slaughterGetInventoryStockData?.updatedNumberOfCarcasses >
            slaughterGetInventoryStockData?.numberOfCarcasses ? (
              <KeyboardDoubleArrowUpIcon color="success" />
            ) : (
              <KeyboardDoubleArrowDownIcon color="error" />
            )}
          </Grid>,
          <Grid container alignItems="center" justifyContent="center" key={"k"}>
            {Number(
              slaughterGetInventoryStockData?.updatedWeightOfCarcasses.toFixed(
                0
              )
            ).toLocaleString()}{" "}
            {slaughterGetInventoryStockData?.updatedWeightOfCarcasses >
            slaughterGetInventoryStockData?.weightOfCarcasses ? (
              <KeyboardDoubleArrowUpIcon color="success" />
            ) : (
              <KeyboardDoubleArrowDownIcon color="error" />
            )}
          </Grid>,

          <Grid container alignItems="center" justifyContent="center" key={"k"}>
            {Number(
              slaughterGetInventoryStockData?.updateAveWeightOfCarcasses.toFixed(
                2
              )
            ).toLocaleString()}
            {slaughterGetInventoryStockData?.updateAveWeightOfCarcasses >
            slaughterGetInventoryStockData?.aveWeightOfCarcasses ? (
              <KeyboardDoubleArrowUpIcon color="success" />
            ) : (
              <KeyboardDoubleArrowDownIcon color="error" />
            )}
          </Grid>,
          slaughterGetInventoryStockData?.freeBarQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.numberOfFreeCarcasses.toLocaleString(),
          slaughterGetInventoryStockData?.freeWeightOfCarcasses.toLocaleString(),
          "سسس",
          "سسس",
          slaughterGetInventoryStockData?.totalBarQuantity.toLocaleString(),
          <Grid container alignItems="center" justifyContent="center" key={"k"}>
            {Number(
              slaughterGetInventoryStockData?.updateTotalNumberOfCarcasses
            ).toLocaleString()}
            {slaughterGetInventoryStockData?.updateTotalNumberOfCarcasses >
            slaughterGetInventoryStockData?.totalNumberOfCarcasses ? (
              <KeyboardDoubleArrowUpIcon color="success" />
            ) : (
              <KeyboardDoubleArrowDownIcon color="error" />
            )}
          </Grid>,
          <Grid container alignItems="center" justifyContent="center" key={"k"}>
            {Number(
              slaughterGetInventoryStockData?.updateTotalWeightOfCarcasses
            ).toLocaleString()}
            {slaughterGetInventoryStockData?.updateTotalWeightOfCarcasses >
            slaughterGetInventoryStockData?.totalWeightOfCarcasses ? (
              <KeyboardDoubleArrowUpIcon color="success" />
            ) : (
              <KeyboardDoubleArrowDownIcon color="error" />
            )}
          </Grid>,
        ],
      ];
    } else {
      data = [
        [
          "سیستمی:",
          slaughterGetInventoryStockData?.barQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.allocatedQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.barLiveWeight.toLocaleString(),
          slaughterGetInventoryStockData?.numberOfCarcasses.toLocaleString(),
          Number(
            slaughterGetInventoryStockData?.weightOfCarcasses.toFixed(0)
          ).toLocaleString(),
          slaughterGetInventoryStockData?.aveWeightOfCarcasses.toFixed(2),
          slaughterGetInventoryStockData?.freeBarQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.numberOfFreeCarcasses.toLocaleString(),
          slaughterGetInventoryStockData?.freeWeightOfCarcasses.toLocaleString(),
          slaughterGetInventoryStockData?.preColdNumberOfCarcassesToWareHouse.toLocaleString(),
          slaughterGetInventoryStockData?.preColdWeightOfCarcassesToWareHouse.toLocaleString(),
          slaughterGetInventoryStockData?.totalBarQuantity.toLocaleString(),
          slaughterGetInventoryStockData?.totalNumberOfCarcasses.toLocaleString(),
          slaughterGetInventoryStockData?.totalWeightOfCarcasses.toLocaleString(),
        ],
      ];
    }
    return data;
  };

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

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

  const isMobile = window.innerWidth <= 600;

  return (
    <Grid
      container
      direction="column"
      alignItems="center"
      justifyContent="start"
    >
      <Grid
        container
        gap={SPACING.SMALL}
        justifyContent="start"
        alignItems="center"
        xs={12}
      >
        <Box sx={{ minWidth: 120 }}>
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">کشتارگاه</InputLabel>
            <Select
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              label="کشتارگاه"
              defaultValue={inventorySelectedKillHouse}
              onChange={handleChangeInventory}
            >
              {profile?.killHouse?.map((item) => {
                return (
                  <MenuItem key={item.key} value={item.key}>
                    {item.name}
                  </MenuItem>
                );
              })}
            </Select>
          </FormControl>
        </Box>

        <DatePicker
          label="تاریخ"
          id="date"
          renderInput={(params) => (
            <TextField style={{ width: "160px" }} {...params} />
          )}
          value={selectedDate1}
          onChange={(e) => {
            setSelectedDate1(moment(e).format("YYYY-MM-DD"));
          }}
        />
      </Grid>
      {isMobile ? (
        <Grid p={SPACING.TINY}>
          <BoxList
            columns={[
              "اطلاعات",
              "تعداد بار",
              "قطعه بار زنده",
              "وزن بار زنده (کیلوگرم)",
              "حجم لاشه استحصالی",
              "وزن لاشه ها استحصالی(کیلوگرم) ",
              "میانگین وزن لاشه ها (کیلوگرم)",
              "تعداد بار (خرید آزاد)",
              "حجم لاشه (خرید آزاد)",
              "وزن لاشه (خرید آزاد) (کیلوگرم)",
              "قطعه پیش سرد",
              "وزن پیش سرد",
              "مجموع بارها",
              "مجموع لاشه ها",
              "مجموع وزن لاشه ها (کیلوگرم)",
            ]}
            data={invenotryStockData()}
          />
        </Grid>
      ) : (
        <SimpleTable
          name={
            <Grid
              container
              gap={SPACING.SMALL}
              alignItems="center"
              justifyContent="space-between"
            >
              <Grid container gap={SPACING.SMALL} alignItems="center">
                <Typography>
                  موجودی انبار تاریخ کشتار {formatJustDate(inventoryDate)}
                </Typography>
                <Tooltip title="خروجی اکسل">
                  <a
                    href={`${axios.defaults.baseURL}inventory/?kill_house_key=${inventorySelectedKillHouse}&date=${selectedDate1}`}
                    rel="noreferrer"
                  >
                    <Button color="success">
                      <RiFileExcel2Fill size={32} />
                    </Button>
                  </a>
                </Tooltip>
              </Grid>
              <Grid container gap={SPACING.SMALL} mb={SPACING.SMALL}>
                {/* <Button
                variant="contained"
                onClick={() => {
                  dispatch(
                    DRAWER({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      title: "ویرایش انبار",
                      content: (
                        <SlaughterEditStock
                          inventoryKey={slaughterGetInventoryStockData?.key}
                          aveWeightOfCarcasses={
                            slaughterGetInventoryStockData?.aveWeightOfCarcasses
                          }
                        />
                      ),
                    })
                  );
                }}
              >
                ویرایش موجودی
              </Button> */}
                <Button
                  variant="contained"
                  onClick={() => {
                    dispatch(
                      DRAWER({
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        title: "خرید آزاد",
                        content: (
                          <SlaughterSubmitFreeBar
                            inventoryKey={slaughterGetInventoryStockData?.key}
                            selectedDate={selectedDate1}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  خرید آزاد
                </Button>
              </Grid>
            </Grid>
          }
          columns={[
            "اطلاعات",
            "تعداد بار",
            "قطعه بار زنده",
            "وزن بار زنده (کیلوگرم)",
            "حجم لاشه استحصالی",
            "وزن لاشه ها استحصالی(کیلوگرم) ",
            "میانگین وزن لاشه ها (کیلوگرم)",
            "تعداد بار (خرید آزاد)",
            "حجم لاشه (خرید آزاد)",
            "وزن لاشه (خرید آزاد) (کیلوگرم)",
            "قطعه پیش سرد",
            "وزن پیش سرد",
            "مجموع بارها",
            "مجموع لاشه ها",
            "مجموع وزن لاشه ها (کیلوگرم)",
          ]}
          data={invenotryStockData()}
        />
      )}

      <Grid mt={SPACING.MEDIUM}>
        <Accordion
          expanded={expanded === "panel1"}
          onChange={handleChange("panel1")}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel1bh-content"
            id="panel1bh-header"
          >
            <Grid container width="100%" gap={SPACING.TINY}>
              <Typography>اطلاعات بارهای سیستمی</Typography>
              <Typography color={"error"}>
                ({inventoryBarsDataTable?.length} مورد)
              </Typography>
            </Grid>
          </AccordionSummary>
          <AccordionDetails>
            {isMobile ? (
              <RespSlaughterStockBarSystem
                data={inventoryBarsDataTable}
                inventorySelectedKillHouse={inventorySelectedKillHouse}
              />
            ) : (
              <AdvancedTable
                columns={[
                  "کدبار",
                  "مرغدار",
                  "کشتارگاه",
                  "کدسفارش",
                  "نوع کشتار",
                  "شهر مرغدار",
                  "تاریخ کشتار",
                  "نژاد",
                  "دامپزشک فارم",
                  "دامپزشک کشتارگاه",
                  "راننده/نوع خودرو",
                  "کدبهداشتی حمل و نقل",
                  "کدرهگیری سامانه قرنطینه",
                  "تعداد تخصیص",
                  "وزن بار (کیلوگرم)",
                  "وضعیت",
                  "مقدار واقعی استحصالی",
                  "وزن واقعی استحصالی",
                  "درصد افت",
                  "عملیات",
                ]}
                data={inventoryBarsDataTable}
              />
            )}
          </AccordionDetails>
        </Accordion>
        <Accordion
          expanded={expanded === "panel2"}
          onChange={handleChange("panel2")}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel1bh-content"
            id="panel1bh-header"
            style={{
              alignItems: "center",
              justifyContent: "center",
              display: "flex",
            }}
          >
            <Grid container width="100%" gap={SPACING.TINY}>
              <Typography>اطلاعات بارهای آزاد</Typography>
              <Typography color={"error"}>
                ({freeBarsDataTable?.length} مورد)
              </Typography>
            </Grid>
          </AccordionSummary>
          <AccordionDetails>
            <AdvancedTable
              // name="اطلاعات بارهای آزاد"
              columns={[
                "فروشنده",
                "نوع خرید",
                "استان/شهر",
                "تاریخ خرید",
                "دامپزشک فارم",
                "ماشین",
                "راننده",
                "کدقرنطینه",
                "حجم",
                "وزن زنده (کیلوگرم)",
                "حجم لاشه",
                "وزن لاشه (کیلوگرم)",
                "بارگذاری بارنامه",
                "عملیات",
              ]}
              data={freeBarsDataTable}
            />
          </AccordionDetails>
        </Accordion>
      </Grid>
    </Grid>
  );
};
