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 { useReactToPrint } from "react-to-print";
import { useRef } from "react";
import { LineWithText } from "../../../../components/line-with-text/LineWithText";
import { useEffect } from "react";
import { useState } from "react";
import ProvinceSendLetterDeclarationNeedFactor from "../province-send-letter-declaration-need-factor/ProvinceSendLetterDeclarationNeedFactor";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import axios from "axios";
import { useDispatch } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";

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

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

  const handleDownloadFactor = async () => {
    try {
      dispatch(LOADING_START());
      let response = await axios.get(
        `Poultry_Request/?role=${getRoleFromUrl()}&today&date1=${selectedDate1}&date2=${selectedDate1}&search=filter&value=${""}&page=1&page_size=1000`
      );
      dispatch(LOADING_END());
      setFactorData(response.data.results);
    } 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"
      // spacing={2}
      gap={2}
      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" }}>
        <ProvinceSendLetterDeclarationNeedFactor
          ref={componentRef}
          sDate={selectedDate1}
          date={selectedDate2}
          fnumber={formik.values.formNumber}
          receiver={formik.values.receiver}
          item={factorData}
        />
      </div>
    </Grid>
  );
};
