import React, { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  Select,
  TextField
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { Tab, Tabs } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { SlaughterShowProducts } from "../slaughter-show-products/SlaughterShowProducts";
import { SlaughterInventoryInProvinceBars } from "../slaughter-inventory-in-province-bars/SlaughterInventoryInProvinceBars";
import { SlaughterInventoryFreeBuyBars } from "../slaughter-inventory-free-buy-bars/SlaughterInventoryFreeBuyBars";
import { slaughterGetBarsInfo } from "../../services/slaughter-get-distribution-info";
import { useDispatch } from "react-redux";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { useSelector } from "react-redux";
import { RiSearchLine } from "react-icons/ri";

export const SlaughterInventory = () => {
  const [value, setValue] = useState("0");
  const [barsInfo, setBarsInfo] = useState([]);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const dispatch = useDispatch();

  // Shared filter state for both province bars tables
  const [selectedDate1, setSelectedDate1] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const [selectedDate2, setSelectedDate2] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const [withDate, setWithDate] = useState(false);
  const [textValue, setTextValue] = useState("");
  const [quota, setQuota] = useState("all");
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  const filterValues = {
    selectedDate1,
    selectedDate2,
    withDate,
    textValue,
    quota
  };

  const handleFilterSubmit = () => {
    setRefreshTrigger((t) => t + 1);
  };

  useEffect(() => {
    dispatch(
      slaughterGetBarsInfo({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : ""
      })
    ).then((r) => {
      setBarsInfo(r.payload.data);
    });
  }, [dispatch, selectedSubUser?.key]);

  return (
    <Grid container xs={12} justifyContent="end" alignItems="center">
      <Grid container width="100%" isDashboard>
        <SlaughterShowProducts />
      </Grid>

      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="center"
        mt={2}
      >
        <Tabs
          value={value}
          onChange={handleChange}
          textColor="secondary"
          indicatorColor="secondary"
          aria-label="secondary tabs example"
        >
          <Tab value="0" label="بارهای داخل استان" />
          <Tab value="1" label="خریدهای خارج استان" />
        </Tabs>
      </Grid>

      {value === "0" && (
        <Grid container xs={12} justifyContent="center" alignItems="center">
          <Grid container justifyContent="start" alignItems="center" xs={12}>
            <ResponsiveTable
              title="اطلاعات کلی بارها"
              noPagination
              data={[
                [
                  barsInfo?.totalBars?.toLocaleString(),
                  barsInfo?.totalBarsQuantity?.toLocaleString(),
                  barsInfo?.totalBarsWeight?.toLocaleString(),
                  barsInfo?.totalEnteredBars?.toLocaleString(),
                  barsInfo?.totalEnteredBarsWeight?.toLocaleString(),
                  barsInfo?.totalEnteredBarsCarcasses?.toLocaleString(),
                  barsInfo?.totalEnteredBarsCarcassesWeight?.toLocaleString(),
                  barsInfo?.totalNotEnteredBars?.toLocaleString(),
                  barsInfo?.totalNotEnteredBarsQuantity?.toLocaleString(),
                  barsInfo?.totalNotEnteredKillHouseRequestsWeight?.toLocaleString()
                ]
              ]}
              columns={[
                "تعداد کل بارها",
                "حجم کل بارها (قطعه)",
                "وزن کل بارها (کیلوگرم)",
                "تعداد کل بارهای وارد شده",
                "وزن کل بارهای وارد شده",
                "حجم کل لاشه وارد شده (قطعه)",
                "وزن کل لاشه وارد شده (کیلوگرم)",
                "تعداد کل بارهای وارد نشده",
                "حجم کل بار وارد نشده (قطعه)",
                "وزن کل بار وارد نشده (کیلوگرم)"
              ]}
              allColors={{ color: "#f3bda3", text: "#332a3d" }}
            />
            <Grid
              container
              xs={12}
              justifyContent="start"
              alignItems="center"
              gap={2}
              pt={SPACING.MEDIUM}
            >
              <Grid
                container
                style={{
                  borderStyle: "solid",
                  borderWidth: "1px",
                  padding: "10px",
                  borderRadius: "15px",
                  borderColor: "gray",
                  justifyContent: "left"
                }}
              >
                <Grid>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={withDate}
                        onChange={() => setWithDate(!withDate)}
                        color="primary"
                      />
                    }
                    label="فیلتر تاریخ"
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    disabled={!withDate}
                    label="از تاریخ"
                    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="تا تاریخ"
                    renderInput={(params) => (
                      <TextField
                        size="small"
                        style={{ width: "160px" }}
                        {...params}
                      />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
              </Grid>
              <Grid>
                <FormControl size="small" style={{ minWidth: 150 }}>
                  <InputLabel>نوع فروش</InputLabel>
                  <Select
                    value={quota}
                    onChange={(e) => setQuota(e.target.value)}
                    label="نوع فروش"
                  >
                    <MenuItem value="all">همه</MenuItem>
                    <MenuItem value="governmental">دولتی</MenuItem>
                    <MenuItem value="free">آزاد</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid>
                <TextField
                  size="small"
                  label="جستجو"
                  variant="outlined"
                  style={{ width: 250 }}
                  value={textValue}
                  onChange={(e) => setTextValue(e.target.value)}
                />
                <Button
                  sx={{ ml: 1 }}
                  variant="contained"
                  onClick={handleFilterSubmit}
                  endIcon={<RiSearchLine />}
                >
                  جستجو
                </Button>
              </Grid>
            </Grid>

            <Grid container mt={SPACING.MEDIUM} mb={SPACING.MEDIUM}>
              <SlaughterInventoryInProvinceBars
                type="notentered"
                useExternalFilters
                filterValues={filterValues}
                onAfterUpdate={() => setRefreshTrigger((t) => t + 1)}
                refreshTrigger={refreshTrigger}
              />
            </Grid>

            <Grid container mt={SPACING.MEDIUM} mb={SPACING.MEDIUM}>
              <SlaughterInventoryInProvinceBars
                type="entered"
                useExternalFilters
                filterValues={filterValues}
                refreshTrigger={refreshTrigger}
              />
            </Grid>
          </Grid>
        </Grid>
      )}

      {value === "1" && (
        <Grid container mt={SPACING.MEDIUM} mb={SPACING.MEDIUM}>
          <SlaughterInventoryFreeBuyBars />
        </Grid>
      )}
    </Grid>
  );
};
