import React, { useEffect, useRef, useState } from "react";
import { Box, Divider, Typography } from "@mui/material";
import { useParams } from "react-router-dom";
import { useReactToPrint } from "react-to-print";
import { useDispatch } from "react-redux";
import moment from "moment";
import ProvinceSendLetterFactorReport from "../features/province/components/province-send-letter-factor-report/ProvinceSendLetterFactorReport";
import { provinceGetAllocationLetterReport } from "../features/province/services/province-get-allocation-letter-report";
import { Grid } from "../components/grid/Grid";

const DownloadReport = () => {
  const styles = {
    container: {
      display: "flex",
      flexDirection: "column",
      alignItems: "center",
    },
    box: {
      border: "1px solid #ccc",
      borderRadius: "4px",
      padding: "10px",
      marginBottom: "20px",
    },
    innerBox: {
      border: "1px solid #eee",
      borderRadius: "4px",
      padding: "5px",
      marginBottom: "5px",
      backgroundColor: "#fbfbea",
    },
  };

  const { name } = useParams();

  const componentRef = useRef();

  const [factorData, setFactorData] = useState(null);
  const dispatch = useDispatch();

  const handleDownloadFactorDailySlaughter = () => {
    try {
      const result = dispatch(
        provinceGetAllocationLetterReport(
          moment(new Date()).format("YYYY-MM-DD")
        )
      );
      setFactorData(result);
    } catch (error) {
      console.error(error);
    }
  };

  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: "گزارش کشتار روزانه",
  });

  // useEffect(() => {
  //   if (factorData) {
  //     printPDF();
  //   }
  // }, [factorData, printPDF]);

  useEffect(() => {
    if (name === "ds") {
      handleDownloadFactorDailySlaughter();
    }
  }, []);

  return (
    <Box
    // sx={{
    //   justifyContent: "center",
    //   alignItems: "center",
    //   height: "100vh",
    //   backgroundColor: "#f0f0f0",
    //   paddingTop: "15%",
    // }}
    >
      <div style={{ marginTop: "10px" }}>
        <h4
          style={{
            textDecoration: "underline",
            color: "blue",
            cursor: "pointer",
          }}
          onClick={() => {
            printPDF();
          }}
        >
          جهت دانلود گزارش بصورت فایل پی دی اف کلیک کنید.
        </h4>

        <Grid container xs={12} justifyContent="center">
          <Grid container xs={10} spacing={2} justifyContent="start">
            {factorData?.payload?.data?.allocation?.map((item, i) => (
              <Grid key={i} xs={12} sm={3} lg={2}>
                <Box style={styles.box}>
                  <Typography color="primary" variant="h6">
                    ردیف: {i + 1}
                  </Typography>
                  <Typography>نام خریدار: {item?.name}</Typography>
                  <Typography>
                    تلفن: {item?.killHouseOperator?.user?.mobile}
                  </Typography>
                  <Typography>
                    شهر: {item?.killHouseOperator?.user?.city?.cityName}
                  </Typography>
                  <Typography>تعداد کل: {item?.totalQuantity}</Typography>
                  <Divider />
                  <Typography color="error" variant="subtitle1">
                    جزئیات سفارش
                  </Typography>
                  {item?.provinceKillRequest?.map((pkRequest, pkIndex) => (
                    <Box key={pkIndex} style={styles.innerBox}>
                      <Typography>مرغدار: {pkRequest?.poultry}</Typography>
                      <Typography>
                        تلفن مرغدار: {pkRequest?.poultryMobile}
                      </Typography>
                      <Typography>تعداد: {pkRequest?.quantity}</Typography>
                      <Typography>
                        میانگین وزن: {pkRequest?.IndexWeight}
                      </Typography>
                    </Box>
                  ))}
                </Box>
              </Grid>
            ))}
            {factorData?.payload?.data?.outProvince?.map((item, i) => (
              <Grid key={i} xs={12} sm={3} lg={2}>
                <Box style={styles.box}>
                  <Typography color="primary" variant="h6">
                    ردیف: {factorData?.payload?.data?.allocation.length + i + 1}
                  </Typography>
                  <Typography color="error" variant="subtitle1">
                    فروش خارج از استان
                  </Typography>
                  <Divider />
                  <Typography>
                    نام مرغدار: {item?.poultry?.unitName} (
                    {item?.poultry?.user?.mobile})
                  </Typography>
                  <Typography>
                    نام خریدار: {item?.buyer?.firstName} {item?.buyer?.lastName}
                  </Typography>
                  <Typography>تلفن: {item?.buyer?.mobile}</Typography>
                  <Typography>شهر: {item?.buyer?.city}</Typography>
                  <Typography>میانگین وزن: {item?.IndexWeight}</Typography>
                  <Typography>تعداد کل: {item?.quantity}</Typography>
                  <Typography>
                    نوع: {item?.freezing ? "انجماد" : "معمولی"}
                  </Typography>
                </Box>
              </Grid>
            ))}
          </Grid>
        </Grid>
        <div
          style={{
            visibility: "hidden",
            position: "absolute",
            overflow: "hidden",
            width: 0,
            height: 0,
          }}
        >
          <div style={{ width: "100%" }}>
            <ProvinceSendLetterFactorReport
              ref={componentRef}
              sDate={moment(new Date()).format("YYYY-MM-DD")}
              date={moment(new Date()).format("YYYY-MM-DD hh:mm:ss")}
              fnumber={moment(new Date()).format("YYYYMMDD")}
              receiver={
                "معاونت محترم بهبود تولیدات دامی سازمان جهاد کشاورزی استان "
              }
              item={factorData?.payload?.data?.allocation}
              itemOutProvince={factorData?.payload?.data?.outProvince}
            />
          </div>
        </div>
      </div>
    </Box>
  );
};

export default DownloadReport;
