import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import axios from "axios";
import { useDispatch } from "react-redux";
import moment from "moment";
import { RiFileExcel2Fill } from "react-icons/ri";
import { Button, Tooltip, Checkbox, TextField } from "@mui/material";
import { dashboardGetSlaughterInformationService } from "../../services/dashboard-slaughter-get-information";
import { AppContext } from "../../../../contexts/AppContext";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provinceGetDispenserKillhousesService } from "../../../province/services/province-get-dispenser-killhouses";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import { DatePicker } from "@mui/x-date-pickers";

export const DashboardSlaughterInformation = () => {
  const [openNotif, , selectedDate1, , selectedDate2] = useContext(AppContext);

  const [dashboardData, setDashboardData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [withDate, setWithDate] = useState(true);
  const [selectedDate3, setSelectedDate3] = useState(
    moment().format("YYYY-MM-DD")
  );
  const [selectedDate4, setSelectedDate4] = useState(
    moment().format("YYYY-MM-DD")
  );
  const dispatch = useDispatch();

  useEffect(() => {
    fetchTableData();
    fetchDashboardData();
  }, [selectedDate1, selectedDate2, selectedDate3, selectedDate4, withDate]);

  const fetchDashboardData = () => {
    dispatch(
      dashboardGetSlaughterInformationService({
        date1: selectedDate1,
        date2: selectedDate2,
      })
    )
      .then((r) => {
        if (r.payload?.data) {
          const d = r.payload.data.map((item, i) => {
            return [
              i + 1,
              item?.killer ? "کشتارکن" : "کشتارگاه",
              item?.name || "",
              `${item?.killHouseOperator?.user?.fullname} (${item?.killHouseOperator?.user?.mobile})` ||
                "-",
              item?.killHouseOperator?.user?.city?.toLocaleString() || "-",
              item?.killingInfo?.killHouseRequestsCount?.toLocaleString() ||
                "0",
              item?.killingInfo?.killHouseRequestsQuantity?.toLocaleString() ||
                "0",
              item?.killingInfo?.killHouseRequestsWeight?.toLocaleString() ||
                "0",
              item?.killingInfo?.killHouseFreeBarCount?.toLocaleString() || "0",
              item?.killingInfo?.killHouseFreeBarQuantity?.toLocaleString() ||
                "0",
              item?.killingInfo?.killHouseFreeBarWeight?.toLocaleString() ||
                "0",
              item?.killingInfo?.provinceKillRequestsQuantity?.toLocaleString() ||
                "0",
              item?.killingInfo?.totalQuantity?.toLocaleString() || "0",
              item?.killingInfo?.totalWeight?.toLocaleString() || "0",
              item?.killingInfo?.totalAvgWeight?.toLocaleString() || "0",
              item?.killingInfo?.killHouseRequestsWareHouseTrueQuantity?.toLocaleString() ||
                "0",
              item?.killingInfo?.killHouseRequestsWareHouseTrueWeight?.toLocaleString() ||
                "0",
              item?.killingInfo?.killHouseRequestsWareHouseFalseQuantity?.toLocaleString() ||
                "0",
              item?.killingInfo?.killHouseRequestsWareHouseFalseWeight?.toLocaleString() ||
                "0",
            ];
          });
          setDashboardData(d);
        }
      })
      .catch((error) => {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "خطا در دریافت اطلاعات کشتارگاه",
          severity: "error",
        });
        console.error("Error fetching dashboard data:", error);
      });
  };

  const fetchTableData = () => {
    dispatch(
      provinceGetDispenserKillhousesService(
        withDate
          ? {
              selectedDate1: selectedDate3,
              selectedDate2: selectedDate4,
            }
          : {}
      )
    )
      .then((r) => {
        const d = r.payload?.data?.map((item, i) => {
          return [
            i + 1,
            `${item?.killHouseOperator?.user?.fullname} (${item?.killHouseOperator?.user?.mobile})`,
            `${item?.killer ? "کشتارکن" : "کشتارگاه"} (${item?.name})`,
            item?.killHouseOperator?.user?.city?.name,
            item?.wareHouseInfo?.productRemainWeight?.toLocaleString(),
            item?.wareHouseInfo?.totalSell?.toLocaleString(),
            item?.wareHouseInfo?.totalKillHouseAllocationsWeight?.toLocaleString(),
            item?.wareHouseInfo?.totalKillHouseFreeSale_barCarcassesWeight?.toLocaleString(),
            <Tooltip title="خروجی اکسل" key={i}>
              <Button
                color="success"
                size="small"
                onClick={() => {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                    severity: "success",
                  });
                  const link = `${
                    axios.defaults.baseURL
                  }kill_house_inventory_data/?&role=KillHouse&key=${
                    item?.killHouseOperator?.user?.key
                  }${
                    withDate
                      ? `&date1=${selectedDate3}&date2=${selectedDate4}`
                      : ``
                  }`;
                  window.location.href = link;
                }}
              >
                <RiFileExcel2Fill size={24} />
              </Button>
            </Tooltip>,
          ];
        });
        setTableData(d);
      })
      .catch((error) => {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "خطا در دریافت اطلاعات توزیع",
          severity: "error",
        });
        console.error("Error fetching table data:", error);
      });
  };

  return (
    <Grid container xs={12} justifyContent="start" alignItems="center" gap={2}>
      <ResponsiveTable
        title="اطلاعات کشتار زنده کشتارگاه"
        noPagination
        columns={[
          "ردیف",
          "ماهیت",
          "کشتارگاه / کشتارکن",
          "مالک",
          "شهر",
          "تعداد بارهای داخل استان",
          "حجم بارهای داخل استان",
          "وزن بارهای داخل استان",
          "تعداد بارهای خارج استان",
          "حجم بارهای خارج استان",
          "وزن بارهای خارج استان",
          "حجم تخصیصات بدون بار",
          "حجم کل بارها",
          "وزن کل بارها",
          "میانگین وزن",
          "حجم وارد شده به انبار",
          "وزن وارد شده به انبار",
          "حجم وارد نشده به انبار",
          "وزن وارد نشده به انبار",
        ]}
        data={dashboardData}
        // sx={{
        //   "& .MuiTableCell-root": {
        //     fontSize: "0.75rem",
        //     padding: "8px",
        //   },
        //   "& .MuiTableHead-root": {
        //     "& .MuiTableCell-root": {
        //       fontWeight: 600,
        //     },
        //   },
        // }}
      />

      <Grid
        container
        mt={2}
        mb={2}
        style={{
          display: "flex",
          alignItems: "center",
          borderStyle: "solid",
          borderWidth: "1px",
          padding: "10px",
          borderRadius: "15px",
          borderColor: "gray",
        }}
        sx={{
          justifyContent: { xs: "start", sm: "center" },
        }}
        gap={1}
      >
        <Grid container justifyContent="center" alignItems="center">
          <Checkbox
            icon={<ToggleOffOutlinedIcon />}
            checkedIcon={<ToggleOnIcon />}
            checked={withDate}
            onChange={() => setWithDate(!withDate)}
            color="primary"
            size="large"
          />
        </Grid>
        <Grid>
          <DatePicker
            disabled={!withDate}
            label="از تاریخ"
            id="date3"
            renderInput={(params) => (
              <TextField
                size="small"
                sx={{ width: { xs: "32vw", sm: "160px" } }}
                {...params}
              />
            )}
            value={moment(selectedDate3)}
            onChange={(newValue) => {
              setSelectedDate3(moment(newValue).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            disabled={!withDate}
            label="تا تاریخ "
            id="date4"
            renderInput={(params) => (
              <TextField
                size="small"
                sx={{ width: { xs: "32vw", sm: "160px" } }}
                {...params}
              />
            )}
            value={moment(selectedDate4)}
            onChange={(newValue) => {
              setSelectedDate4(moment(newValue).format("YYYY-MM-DD"));
            }}
            minDate={moment(selectedDate3)}
          />
        </Grid>
      </Grid>

      <ResponsiveTable
        title="اطلاعات توزیع گوشت مرغ کشتارگاه"
        noPagination
        columns={[
          "ردیف",
          "خریدار",
          "ماهیت",
          "شهر",
          "مانده انبار فعلی",
          "وزن کل فروش (لاشه)",
          "وزن فروش داخل استان(لاشه)",
          "وزن فروش خارج استان(لاشه)",
          "خروجی اکسل",
        ]}
        data={tableData}
        sx={{
          "& .MuiTableCell-root": {
            fontSize: "0.75rem",
            padding: "8px",
          },
          "& .MuiTableHead-root": {
            "& .MuiTableCell-root": {
              fontWeight: 600,
            },
          },
        }}
      />
    </Grid>
  );
};
