import React, { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  Button,
  FormControlLabel,
  IconButton,
  Radio,
  RadioGroup,
  TextField,
  Tooltip,
} from "@mui/material";
import SystemUpdateAltIcon from "@mui/icons-material/SystemUpdateAlt";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import axios from "axios";
import { useLocation } from "react-router-dom";
import { ROUTE_STEWARD_INVENTORY } from "../../../../routes/routes";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const StewardShowProducts = () => {
  const { distributionInfo, stewardProducts } = useSelector(
    (state) => state.stewardSlice
  );
  const [productsTable, setProductsTable] = useState();
  const { pathname } = useLocation();

  const dispatch = useDispatch();

  const getWeight = (item) => {
    if (getRoleFromUrl() === "KillHouse") {
      return [
        item?.totalGovernmentalCarcassesWeight?.toLocaleString(),
        item?.provinceFreeCarcassesWeight?.toLocaleString(),
      ];
    } else {
      return [
        item?.receiveGovernmentalCarcassesWeight?.toLocaleString(),
        item?.receiveFreeCarcassesWeight?.toLocaleString(),
      ];
    }
  };

  useEffect(() => {
    const d = stewardProducts?.map((item, i) => {
      return [
        i + 1,
        item?.name,
        ...getWeight(item),
        item?.freeBuyingCarcassesWeight?.toLocaleString(),
        item?.totalCarcassesWeight?.toLocaleString(),
        item?.realAllocatedWeight?.toLocaleString(),
        item?.totalRemainWeight?.toLocaleString(),
        distributionInfo?.totalGovernmentalRemainWeight?.toLocaleString(),
        distributionInfo?.totalFreeRemainWeight?.toLocaleString(),
        distributionInfo?.totalGovernmentalInputWeight?.toLocaleString(),
        distributionInfo?.totalFreeInputWeight?.toLocaleString(),
      ];
    });

    setProductsTable(d);
  }, [stewardProducts, distributionInfo]);

  const getDistributionKeys = () => {
    if (pathname === ROUTE_STEWARD_INVENTORY) {
      return [];
    } else {
      return [
        "مانده دولتی (کیلوگرم)",
        " مانده آزاد  (کیلوگرم)",
        "وزن دولتی (کیلوگرم)",
        "وزن آزاد (کیلوگرم)",
      ];
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center">
      <ResponsiveTable
        noPagination={productsTable?.length === 1}
        paginated={!productsTable?.length === 1}
        operation={
          <Grid container>
            {getRoleFromUrl() === "KillHouse" && (
              <Tooltip title="خروجی اکسل" placement="top">
                <IconButton
                  color="primary"
                  onClick={() => {
                    dispatch(
                      OPEN_MODAL({
                        title: "دریافت خروجی اکسل",
                        content: <HandleDownloadInventoryData />,
                      })
                    );
                  }}
                >
                  <SystemUpdateAltIcon />
                </IconButton>
              </Tooltip>
            )}
          </Grid>
        }
        title={"موجودی انبار"}
        columns={[
          "ردیف",
          "نام محصول",
          "وزن خریدهای دولتی داخل استان (کیلوگرم)",
          "وزن خریدهای آزاد داخل استان (کیلوگرم)",
          "وزن خریدهای خارج استان (کیلوگرم)",
          "کل ورودی به انبار (کیلوگرم)",
          "کل فروش (کیلوگرم)",
          "مانده انبار (کیلوگرم)",
          ...getDistributionKeys(),
        ]}
        data={productsTable}
        customColors={[
          { name: "ردیف", color: "red" },
          { name: "نام محصول", color: "red" },
          { name: "کل ورودی به انبار (کیلوگرم)", color: "red" },
          { name: "وزن خریدهای دولتی داخل استان (کیلوگرم)", color: "red" },
          { name: "وزن خریدهای آزاد داخل استان (کیلوگرم)", color: "red" },
          { name: "وزن خریدهای خارج استان (کیلوگرم)", color: "red" },
          { name: "کل فروش (کیلوگرم)", color: "red" },
          { name: "مانده انبار (کیلوگرم)", color: "green" },
        ]}
      />
    </Grid>
  );
};

const HandleDownloadInventoryData = () => {
  const [downloadType, setDownloadType] = useState("withdate");
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const handleChange = (event) => {
    setDownloadType(event.target.value);
  };

  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);
  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <RadioGroup
        row
        aria-labelledby="radio-group-label"
        name="radio-buttons-group"
        value={downloadType}
        onChange={handleChange}
      >
        <FormControlLabel
          value="withdate"
          control={<Radio />}
          label="دانلود بر اساس بازه"
        />
        <FormControlLabel
          value="nodate"
          control={<Radio />}
          label="دانلود کلی"
        />
      </RadioGroup>

      {downloadType === "withdate" && (
        <Grid
          container
          xs={12}
          justifyContent="center"
          alignItems="center"
          gap={2}
        >
          <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>
            <DatePicker
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField style={{ width: "160px" }} {...params} />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>
      )}

      <Button
        fullWidth
        variant="contained"
        onClick={() => {
          dispatch(CLOSE_MODAL());
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
            severity: "success",
          });
          const link = `${
            axios.defaults.baseURL
          }kill_house_inventory_data/?role=${getRoleFromUrl()}${
            checkPathStartsWith("steward")
              ? `&role_key=${selectedSubUser?.key}`
              : ""
          }&key=${userKey}${
            downloadType === "withdate"
              ? `&date1=${selectedDate1}&date2=${selectedDate2}`
              : ``
          }`;
          window.location.href = link;
        }}
      >
        دانلود فایل اکسل
      </Button>
    </Grid>
  );
};
