import React, { useContext } from "react";
import { Autocomplete, 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 { useDispatch } from "react-redux";
import { useState } from "react";
import { provinceGetSlaughterLetter } from "../../services/province-get-slaughter-letter";
import { provinceGetQuarantineLetter } from "../../services/province-get-quarantine-letter";
import ProvinceQuarantineInvoice from "../province-quarantine-invoice/ProvinceQuarantineInvoice";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";

export const ProvinceSendLetterTransferSlaughter = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const componentRef = useRef();
  const [options, setOptions] = useState("");
  const [selectedOption, setSelectedOption] = useState(null);

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

  const handleDownloadFactor = () => {
    const result = dispatch(
      provinceGetQuarantineLetter(formik2.values.userInfoCheck)
    );
    setFactorData(result);
  };

  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: "فاکتور قرنطینه",
    onAfterPrint: () => {
      setFactorData(null);
    },
  });

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

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

  const formik2 = useFormik({
    initialValues: {
      userInfoCheck: "",
    },
    validationSchema: Yup.object({
      userInfoCheck: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });

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

  useEffect(() => {
    dispatch(provinceGetSlaughterLetter(selectedDate1)).then((r) => {
      setOptions(r.payload.data);
      setSelectedOption(null);
    });
  }, [selectedDate1]);

  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={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}>
        <Autocomplete
          sx={{ width: "100%" }}
          id="userInfoCheck"
          getOptionDisabled={(option) => {
            return option.disabled <= 0;
          }}
          options={
            options
              ? options?.map((i) => ({
                  id: i.orderCode,
                  label: i?.poultry?.unitName + ` (${i.poultry?.user?.mobile})`,
                }))
              : []
          }
          getOptionLabel={(option) => option.label}
          value={selectedOption}
          onChange={(event, newValue) => {
            setSelectedOption(newValue);
            formik2.setFieldValue("userInfoCheck", newValue ? newValue.id : "");
          }}
          onBlur={formik2.handleBlur}
          renderInput={(params) => (
            <TextField
              {...params}
              label="مرغدار"
              variant="outlined"
              fullWidth
            />
          )}
        />
      </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}>
        <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}>
        <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"
          fullWidth
        />
      </Grid>

      <Grid item xs={12} sm={6} md={4} lg={3}>
        <NumberInput
          allowLeadingZeros
          thousandSeparator=","
          fullWidth
          id="price"
          label="قیمت روز مرغ (ریال)"
          variant="outlined"
          value={formik.values.price}
          error={formik.touched.price ? Boolean(formik.errors.price) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.price && Boolean(formik.errors.price)
              ? formik.errors.price
              : null
          }
        />
      </Grid>

      <Grid item xs={12} sm={6} md={4} lg={3}>
        <Tooltip title="تولید خروجی PDF">
          <Button
            disabled={!(formik.isValid && formik2.values.userInfoCheck)}
            onClick={handleDownloadFactor}
            variant="contained"
            fullWidth
          >
            صدور نامه
          </Button>
        </Tooltip>
      </Grid>

      <div style={{ display: "none", position: "absolute" }}>
        <ProvinceQuarantineInvoice
          ref={componentRef}
          sDate={selectedDate1}
          date={selectedDate2}
          fnumber={formik.values.formNumber}
          receiver={formik.values.receiver}
          item={factorData?.payload?.data}
          price={formik.values.price}
        />
      </div>
    </Grid>
  );
};
