import React, { useContext } from "react";
import { Button, TextField, Tooltip } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import ProvinceSendLetterFactor from "../province-send-letter-factor/ProvinceSendLetterFactor";
import { useReactToPrint } from "react-to-print";
import { useRef } from "react";
import { LineWithText } from "../../../../components/line-with-text/LineWithText";
import { useEffect } from "react";
import { provinceGetAllocationLetter } from "../../services/province-get-allocation-letter";
import { useDispatch } from "react-redux";
import { useState } from "react";

export const ProvinceSendLetterDailySlaughter = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

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

  const handleDownloadFactor = () => {
    try {
      const result = dispatch(provinceGetAllocationLetter(selectedDate1));
      setFactorData(result);
    } catch (error) {
      console.error(error);
    }
  };

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

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

  const formik = useFormik({
    initialValues: {
      receiver: "",
      formNumber: "",
    },
    validationSchema: Yup.object({
      receiver: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا مشخصات دریافت کننده را وارد کنید!"),
      formNumber: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid
      container
      mb={2}
      mt={2}
      alignItems="center"
      justifyContents="center"
      gap={2}
      xs={12}
      px={2}
    >
      <Grid item xs={12}>
        <LineWithText
          sx={{ alignSlef: "center", textAlign: "center" }}
          text="صدور نامه گزارش کشتار روزانه"
        />
      </Grid>
      <Grid item xs={12} sm={6} md={6} lg={6}>
        <TextField
          id="receiver"
          label="مثال: معاونت محترم توسعه بازرگانی و صنایع کشاورزی"
          value={formik.values.receiver}
          error={
            formik.touched.receiver ? Boolean(formik.errors.receiver) : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.receiver && Boolean(formik.errors.receiver)
              ? formik.errors.receiver
              : null
          }
          autoComplete="current-password"
          variant="outlined"
          fullWidth
        />
      </Grid>

      <Grid item xs={12} sm={6} md={4} lg={3}>
        <TextField
          id="formNumber"
          label="شماره نامه را وارد کنید"
          value={formik.values.formNumber}
          error={
            formik.touched.formNumber ? Boolean(formik.errors.formNumber) : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.formNumber && Boolean(formik.errors.formNumber)
              ? formik.errors.formNumber
              : null
          }
          autoComplete="current-password"
          variant="outlined"
        />
      </Grid>
      <Grid item xs={12} sm={6} md={4} lg={3}>
        <DatePicker
          label="تاریخ کشتار"
          id="date"
          renderInput={(params) => <TextField {...params} fullWidth />}
          value={selectedDate1}
          onChange={(e) => {
            setSelectedDate1(moment(e).format("YYYY-MM-DD"));
          }}
        />
      </Grid>
      <Grid item xs={12} sm={6} md={4} lg={3}>
        <DatePicker
          label="تاریخ نامه"
          id="date"
          renderInput={(params) => <TextField {...params} fullWidth />}
          value={selectedDate2}
          onChange={(e) => {
            setSelectedDate2(moment(e).format("YYYY-MM-DD"));
          }}
        />
      </Grid>

      <Grid item xs={12} sm={6} md={4} lg={3}>
        <Tooltip title="تولید خروجی PDF">
          <Button
            fullWidth
            disabled={!formik.isValid}
            onClick={() => {
              handleDownloadFactor();
            }}
            variant="contained"
          >
            صدور نامه
          </Button>
        </Tooltip>
      </Grid>
      <div style={{ display: "none", position: "absolute" }}>
        <ProvinceSendLetterFactor
          ref={componentRef}
          sDate={selectedDate1}
          date={selectedDate2}
          fnumber={formik.values.formNumber}
          receiver={formik.values.receiver}
          item={factorData?.payload?.data}
        />
      </div>
    </Grid>
  );
};
