import React, { useEffect, useState } from "react";
import {
  Checkbox,
  FormControlLabel,
  Tab,
  Tabs,
  TextField,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import {
  liveStockGetInventoryData,
  liveStockGetInventoryDataDashboard,
} from "../../../live-stock-support/services/live-stock-get-inventory-data";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SPACING } from "../../../../data/spacing";
import { SlaughterColdHouseBars } from "../slaughter-cold-house-bars/SlaughterColdHouseBars";
import { useParams } from "react-router-dom";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterMorgueView = () => {
  const dispatch = useDispatch();
  const [tableData, setTableData] = useState([]);
  const [tableDataDashboard, setTableDataDashboard] = useState([]);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const { key } = useParams();

  const [withDate, setWithDate] = useState(false);

  const [selectedDate1, setSelectedDate1] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const [selectedDate2, setSelectedDate2] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

  const getDashboardsData = () => {
    dispatch(
      liveStockGetInventoryData({
        dashboard: true,
        cold_house_key: key,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setTableData(r.payload.data);
    });
    dispatch(
      liveStockGetInventoryDataDashboard({
        date1: withDate ? selectedDate1 : null,
        date2: withDate ? selectedDate2 : null,
        cold_house_key: key,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setTableDataDashboard(r.payload.data);
    });
  };
  useEffect(() => {
    getDashboardsData();
  }, [dispatch, withDate, selectedDate1, selectedDate2, selectedSubUser?.key]);

  const [value, setValue] = useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <>
      <Grid container direction="column" justifyContent="center" xs={12}>
        <Grid container justifyContent="space-between" gap={SPACING.SMALL}>
          <ResponsiveTable
            noPagination
            columns={["وزن کل", "وزن خارج شده", "وزن باقیمانده"]}
            data={[
              [
                tableData?.totalInputWeight?.toLocaleString(),
                tableData?.totalAllocatedWeight?.toLocaleString(),
                tableData?.totalRemainWeight?.toLocaleString(),
              ],
            ]}
            title="موجودی سردخانه"
            isDashboard
          />

          <ResponsiveTable
            noPagination
            columns={[
              "تعداد کل بارهای وارد شده",
              "وزن کل بارهای وارد شده",
              "تعداد کل بارهای خارج شده",
              "وزن کل بارهای خارج شده",
            ]}
            data={[
              [
                tableDataDashboard?.totalInputBars?.toLocaleString(),
                tableDataDashboard?.totalInputBarsWeight?.toLocaleString(),
                tableDataDashboard?.totalOutputBars?.toLocaleString(),
                tableDataDashboard?.totalOutputBarsWeight?.toLocaleString(),
              ],
            ]}
            title={"خلاصه اطلاعات"}
            isDashboard
          />
        </Grid>
        <Grid
          container
          alignItems="center"
          justifyContent="space-between"
          gap={2}
          paddingTop={2}
          mb={1}
          width="100%"
        >
          <Grid
            container
            gap={1}
            style={{
              borderStyle: "solid",
              borderWidth: "1px",
              padding: "10px",
              borderRadius: "15px",
              borderColor: "gray",
              justifyContent: "left",
            }}
          >
            <Grid>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={withDate}
                    onChange={() => setWithDate(!withDate)}
                    color="primary"
                  />
                }
              />
            </Grid>
            <Grid>
              <DatePicker
                disabled={!withDate}
                label="از تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField
                    size="small"
                    style={{ width: "160px" }}
                    {...params}
                  />
                )}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Grid>
              <DatePicker
                disabled={!withDate}
                label="تا تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField
                    size="small"
                    style={{ width: "160px" }}
                    {...params}
                  />
                )}
                value={selectedDate2}
                onChange={(e) => {
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
          </Grid>
        </Grid>
        <Grid container xs={12} justifyContent="center">
          <Tabs
            sx={{ mb: 2 }}
            value={value}
            onChange={handleChange}
            aria-label="simple tabs example"
          >
            <Tab value={0} label="بارهای خارج شده" />
            <Tab value={1} label="بارهای وارد شده" />
          </Tabs>
          {value === 0 && (
            <SlaughterColdHouseBars
              selectedDate1={selectedDate1}
              selectedDate2={selectedDate2}
              title="بارهای خارج شده"
              type={"output"}
              withDate={withDate}
              coldHouseKey={key}
              getDashboardsData={getDashboardsData}
              remainWeight={tableData?.totalRemainWeight}
            />
          )}
          {value === 1 && (
            <SlaughterColdHouseBars
              selectedDate1={selectedDate1}
              selectedDate2={selectedDate2}
              title="بارهای وارد شده"
              type={"input"}
              withDate={withDate}
              coldHouseKey={key}
              getDashboardsData={getDashboardsData}
            />
          )}
        </Grid>
      </Grid>
    </>
  );
};
