import React, { useContext, useEffect, useState } from "react";
import {
  Grid,
  Typography,
  Box,
  TextField,
  Tooltip,
  Button,
} from "@mui/material";
import { KillingInformation } from "../dashboard-killing-information/KillingInformation";
import { useDispatch, useSelector } from "react-redux";
import { SPACING } from "../../../../data/spacing";
import { StatBox } from "../dashboard-state-box/StatBox";
import { DashboardAllocationWithOutBar } from "../dashboard-allocation-with-out-bar/DashboardAllocationWithOutBar";
import { DashboardLivePurchase } from "../dashboard-live-purchase/DashboardLivePurchase";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";

import axios from "axios";
import { RiFileExcel2Fill } from "react-icons/ri";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { DashboardBuyingCarcassess } from "../dashboard-buying-carcassess/DashboardBuyingCarcassess";
import { DashboardProvinceSellOut } from "../dashboard-sell-out/DashboardProvinceSellOut";
import { dashboardGetMonitoringBarAndKillingService } from "../../services/dashboard-get-service";
import { DashboardSlaughterInformation } from "../dashboard-slaughter-information/DashboardSlaughterInformation";
import { ImFilePdf } from "react-icons/im";

export const SlaughterDashboard = () => {
  const dispatch = useDispatch();

  const [boxStats, setBoxStats] = useState({
    killingInfo: {},
    bar: {},
    freeLiveBar: {},
    provinceKillRequestWithoutBar: {},
    outLiveBar: {},
    buyFreeCarcasses: {},
  });
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  useEffect(() => {
    dispatch(
      dashboardGetMonitoringBarAndKillingService({
        date1: selectedDate1 || "null",
        date2: selectedDate2 || "null",
      })
    ).then((r) => {
      if (r.payload?.data) {
        setBoxStats(r.payload.data);
      }
    });
  }, [dispatch, selectedDate1, selectedDate2]);

  const firstRowBoxes = [
    {
      title: "تعداد بارها",
      value: boxStats?.bar?.count?.toLocaleString() || 0,
    },
    {
      title: "حجم بارها",
      value: boxStats?.bar?.quantity?.toLocaleString() || 0,
      unit: "قطعه",
    },
    {
      title: "وزن بارها",
      value: boxStats?.bar?.weight?.toLocaleString() || 0,
      unit: "کیلوگرم",
    },
    {
      title: "میانگین سن",
      value: boxStats?.bar?.avgAge?.toLocaleString() || 0,
      unit: "روز",
    },
    {
      title: "میانگین وزن",
      value: boxStats?.bar?.avgWeight?.toLocaleString() || 0,
      unit: "کیلوگرم",
    },
  ];

  const secondRowBoxes = [
    {
      title: "تعداد بارها",
      value: boxStats?.bar?.countHasQuarantine?.toLocaleString() || 0,
    },
    {
      title: "حجم بارهای رصدیار",
      value: boxStats?.bar?.quantityHasQuarantine?.toLocaleString() || 0,
      unit: "قطعه",
    },
    {
      title: "حجم بارهای قرنطینه",
      value: boxStats?.bar?.totalQuarantineQuantity?.toLocaleString() || 0,
      unit: "قطعه",
    },

    {
      title: "اختلاف قطعه",
      value: `${(
        boxStats?.bar?.quantityHasQuarantine -
          boxStats?.bar?.totalQuarantineQuantity || 0
      )?.toLocaleString()}  (${
        boxStats?.bar?.quantityHasQuarantine
          ? (
              ((boxStats?.bar?.quantityHasQuarantine -
                boxStats?.bar?.totalQuarantineQuantity) /
                boxStats?.bar?.quantityHasQuarantine) *
              100
            )?.toFixed(0) + "%)"
          : "0%)"
      }`,
      isNegative:
        boxStats?.bar?.quantityHasQuarantine -
          boxStats?.bar?.totalQuarantineQuantity <
        0,
    },
  ];

  return (
    <Grid container alignItems="center" justifyContent="flex-start">
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
        sx={{
          padding: "12px",
        }}
      >
        <Grid
          container
          gap={1}
          sx={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "8px",
            borderRadius: "15px",
            borderColor: "gray",
            alignItems: "center",
            width: "auto",
            flexWrap: "nowrap",
          }}
        >
          <Grid>
            <DatePicker
              label="از تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: { xs: "45%", sm: "160px" } }}
                  size="small"
                />
              )}
              value={selectedDate1}
              onChange={(newValue) => {
                setSelectedDate1(moment(newValue).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              label="تا تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: { xs: "45%", sm: "160px" } }}
                  size="small"
                />
              )}
              value={selectedDate2}
              onChange={(newValue) => {
                setSelectedDate2(moment(newValue).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>

        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }dashboard_monitoring_bar_and_killing_excel/?&role=${getRoleFromUrl()}&key=${userKey}&date1=${selectedDate1}&date2=${selectedDate2}
            `}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
        <Tooltip title="خروجی پی دی اف">
          <a
            href={`${axios.defaults.baseURL}management_all_poultry_and_warehouse_pdf/?date1=${selectedDate1}&date2=${selectedDate2}
            `}
            rel="noreferrer"
          >
            <Button color="error">
              <ImFilePdf size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <Grid
        container
        // spacing={2}
        xs={12}
        sx={{
          width: "100%",
          display: "flex",
          flexWrap: "wrap",
          gap: SPACING.SMALL,
          justifyContent: "center",
          alignItems: "stretch",
          mt: 2,
        }}
      >
        <KillingInformation boxStats={boxStats} />
        <Grid
          item
          sx={{
            width: { xs: "100%", md: "52%" },
            display: "flex",
            flexDirection: "column",
            gap: SPACING.SMALL,
          }}
        >
          <Box
            sx={{
              width: { xs: "100%" },
              borderRadius: "16px",
              border: "1px solid",
              borderColor: "divider",
              p: {
                md: "10px",
              },
            }}
          >
            <Typography
              sx={{
                padding: "10px",
              }}
              textAlign="start"
              variant="h6"
              color="primary.main"
            >
              اطلاعات بار
            </Typography>

            <Grid
              container
              justifyContent="space-between"
              sx={{ mb: SPACING.SMALL }}
            >
              {firstRowBoxes.map((box, index) => (
                <Grid
                  item
                  key={index}
                  minWidth={{ sm: "150px", xs: "100%" }}
                  sx={{
                    display: "flex",
                    justifyContent: "center",
                    minHeight: "100px",
                  }}
                >
                  <StatBox
                    title={box?.title}
                    value={`${box?.value}`}
                    unit={box?.unit}
                    color={index % 2 === 0 ? "primary" : "secondary"}
                    textColor={box?.value < 0 ? "red" : "primary"}
                  />
                </Grid>
              ))}
            </Grid>
            <Typography
              sx={{
                padding: "10px",
              }}
              textAlign="start"
              variant="h6"
              color="primary.main"
            >
              اطلاعات بارهای دارای استعلام قرنطینه
            </Typography>

            <Grid
              container
              spacing={SPACING.SMALL}
              sx={{ mb: SPACING.SMALL, padding: "10px" }}
            >
              {secondRowBoxes.map((box, index) => (
                <Grid
                  item
                  key={index}
                  xs={12}
                  sm={2.3}
                  sx={{
                    display: "flex",
                    justifyContent: "center",
                    minHeight: "100px",
                  }}
                >
                  <StatBox
                    title={box?.title}
                    value={`${box?.value} ${box?.unit || ""}`}
                    color={index % 2 === 0 ? "primary" : "secondary"}
                    textColor={box?.value < 0 ? "red" : "primary"}
                  />
                </Grid>
              ))}
            </Grid>
          </Box>
        </Grid>
        <Grid
          container
          sx={{
            width: "100%",
            display: "flex",
            flexWrap: "wrap",
            gap: SPACING.SMALL,
            justifyContent: "center",
            alignItems: "stretch",
            mt: 2,
          }}
        >
          <DashboardAllocationWithOutBar boxStats={boxStats} />
          <DashboardLivePurchase boxStats={boxStats} />
        </Grid>

        <Grid
          container
          sx={{
            width: "100%",
            display: "flex",
            flexWrap: "wrap",
            gap: SPACING.SMALL,
            justifyContent: "center",
            alignItems: "stretch",
            mt: 2,
          }}
        >
          <DashboardBuyingCarcassess boxStats={boxStats} />
          <DashboardProvinceSellOut boxStats={boxStats} />
        </Grid>

        <Grid
          container
          sx={{
            width: "95%",
            display: "flex",
            flexWrap: "wrap",
            gap: SPACING.SMALL,
            justifyContent: "center",
            alignItems: "stretch",
            mt: 2,
          }}
        >
          <DashboardSlaughterInformation />
        </Grid>
      </Grid>
    </Grid>
  );
};
