import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import { Button, TextField, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { RiSearchLine } from "react-icons/ri";
import axios from "axios";
import { AppContext } from "../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../lib/redux/slices/appSlice";
import { formatJustDate, formatTime } from "../../../utils/formatTime";
import { StewardSegmentOperation } from "../../guild/components/StewardSegmentOperation";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";
import { Grid } from "../../../components/grid/Grid";
import { SPACING } from "../../../data/spacing";
import ResponsiveTable from "../../../components/responsive-table/ResponsiveTable";
import { checkPathStartsWith } from "../../../utils/checkPathStartsWith";
import { stawardGetSegmentDashboardService } from "../../guild/services/steward-get-dashboard-service";
import { stewardGetOutSellService } from "../../guild/services/steward-get-sell-out-service";
import { StewardSegmentSubmitOperation } from "../../guild/components/StewardSegmentSubmitOperation";

export const SenfSegmentaion = () => {
  const [data, setData] = useState([]);
  const [products, setProducts] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [dashboardData, setDashboardData] = useState([]);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();

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

  const getDashboardData = () => {
    dispatch(
      stawardGetSegmentDashboardService({
        value: textValue,
        date1: selectedDate1,
        date2: selectedDate2,
        role: getRoleFromUrl(),
        role_key:
          checkPathStartsWith("slaughter") || checkPathStartsWith("senf")
            ? selectedSubUser?.key
            : "",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}${
        checkPathStartsWith("slaughter") || checkPathStartsWith("senf")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }`
    );

    getDashboardData();
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };
  const updateTable = () => {
    fetchApiData(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  useEffect(() => {
    fetchApiData(1);
    dispatch(
      stewardGetOutSellService({
        role_key:
          checkPathStartsWith("slaughter") || checkPathStartsWith("senf")
            ? selectedSubUser?.key || ""
            : "",
      })
    ).then((r) => {
      setProducts(r.payload.data);
    });
  }, []);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.productionDate ? formatTime(item?.productionDate) : "-",
        item?.distributionType === "web"
          ? "سایت"
          : item?.distributionType === "app"
          ? "موبایل"
          : item?.distributionType === "pos"
          ? "پوز"
          : item?.distributionType || "-",
        `${item?.buyer?.fullname}(${item?.buyer?.mobile})`,
        item?.toGuild
          ? `به قطعه بند - ${item?.toGuild?.user?.fullname}(${item?.toGuild?.user?.mobile})`
          : "قطعه بندی توسط کشتارگاه",
        item?.date ? formatJustDate(item?.date) : "-",
        item?.weight,
        item?.quota === "governmental"
          ? "دولتی"
          : item?.quota === "free"
          ? "آزاد"
          : "-",
        item?.saleType === "governmental"
          ? "دولتی"
          : item?.saleType === "free"
          ? "آزاد"
          : "-",
        <StewardSegmentOperation
          key={i}
          item={item}
          productKey={products?.[0]?.key}
          updateTable={updateTable}
        />,
      ];
    });

    setTableData(d);
  }, [data]);

  useEffect(() => {
    fetchApiData(1);
  }, [selectedDate1, selectedDate2, perPage, selectedSubUser?.key]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter") || checkPathStartsWith("senf")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      getDashboardData();
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container>
      <Typography variant="h6" my={SPACING.SMALL}>
        ثبت قطعه بندی
      </Typography>
      <Grid
        xs={12}
        container
        alignItems="center"
        gap={SPACING.SMALL}
        justifyContent="flex-start"
      >
        <Grid container mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={[
              "وزن کل (کیلوگرم)",
              // "تخصیصات مباشر",
              "وزن قطعه بندی",
              // "تخصیصات قطعه بند",
              "وزن تخصیصی به قطعه بندها",
            ]}
            data={[
              [
                dashboardData?.totalWeight?.toLocaleString() || "0",
                // dashboardData?.totalSelfCount?.toLocaleString() || "0",
                dashboardData?.totalSelfWeight?.toLocaleString() || "0",
                // dashboardData?.totalOtherCount?.toLocaleString() || "0",
                dashboardData?.totalOtherWeight?.toLocaleString() || "0",
              ],
            ]}
            title={"خلاصه اطلاعات"}
          />
        </Grid>
        <form>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "ثبت قطعه بندی",
                    size: {
                      xs: "100%",
                      sm: "380px",
                    },
                    content: (
                      <StewardSegmentSubmitOperation
                        updateTable={updateTable}
                        productKey={products?.[0]?.key}
                      />
                    ),
                  })
                );
              }}
            >
              ثبت قطعه بندی
            </Button>

            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
            <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>
            {/* <Tooltip title="خروجی اکسل">
              <Button
                color="success"
                onClick={() => {
                  const link = `${
                    axios.defaults.baseURL
                  }kill_house_free_bar_excel/?role=${getRoleFromUrl()}&key=${userKey}&date1=${selectedDate1}&date2=${selectedDate2}&type=carcass&search=filter&value=${textValue}&date_type=buy`;
                  window.location.href = link;
                }}
              >
                <RiFileExcel2Fill size={32} />
              </Button>
            </Tooltip> */}
          </Grid>
        </form>

        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "تاریخ تولید گوشت",
            "ثبت شده",
            "قطعه بند",
            "تخصیص",
            "تاریخ ",
            "وزن (کیلوگرم)",
            "سهمیه",
            "نوع فروش",
            "عملیات",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="قطعه بندی"
        />
      </Grid>
    </Grid>
  );
};
