import React from "react";
import { Grid } from "../../../../components/grid/Grid";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { useContext } from "react";
import moment from "moment";
import {
  Button,
  FormControl,
  FormControlLabel,
  IconButton,
  Radio,
  RadioGroup,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { useState } from "react";
import { useRef } from "react";
import { useReactToPrint } from "react-to-print";
import { useEffect } from "react";
import ProvinceGetReportFile from "../province-get-report-file/ProvinceGetReportFile";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { provinceGetProcessData } from "../../services/province-get-report-process";
import { formatJustDate } from "../../../../utils/formatTime";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useLocation } from "react-router-dom";
import { ROUTE_COMMERCE_REQUESTS } from "../../../../routes/routes";

export default function PorvinceGetReportOperations() {
  const { pathname } = useLocation();
  const [, , selectedDate1, setSelectedDate1] = useContext(AppContext);

  const userInfo = useSelector((state) => state.userSlice);

  const dispatch = useDispatch();

  const [data, setData] = useState();
  const componentRef = useRef();
  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: `گزارش روزانه ${formatJustDate(selectedDate1)}`,
    onAfterPrint: () => {
      setData(null);
    },
  });

  const setPdfOptions = (item) => {
    dispatch(LOADING_START());
    dispatch(provinceGetProcessData({ selectedDate1, value })).then((r) => {
      setData(r.payload.data);
      dispatch(LOADING_END());
    });
  };

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

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

  const [value, setValue] = React.useState("slaughter");

  const handleChange = (event) => {
    setValue(event.target.value);
  };

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

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      justifyContent="center"
      alignItems="center"
    >
      <div style={{ visibility: "hidden", position: "absolute" }}>
        <ProvinceGetReportFile
          ref={componentRef}
          item={data}
          inDate={selectedDate1}
          targetperson={
            pathname === ROUTE_COMMERCE_REQUESTS
              ? "معاونت محترم توسعه بازرگانی و صنایع کشاورزی"
              : formik.values.target
          }
          reportType={value}
        />
      </div>

      <Grid container xs={12} alignItems="center" spacing={2}>
        <Grid xs={12} alignItems="center">
          <FormControl>
            <RadioGroup
              size="small"
              row
              aria-labelledby="demo-controlled-radio-buttons-group"
              name="controlled-radio-buttons-group"
              value={value}
              onChange={handleChange}
            >
              <FormControlLabel
                label="گزارش کشتار"
                control={<Radio size="small" />}
                value="slaughter"
              />
              <FormControlLabel
                label="گزارش پخش"
                control={<Radio size="small" />}
                value="broadcast"
              />
            </RadioGroup>
          </FormControl>
        </Grid>

        {pathname !== ROUTE_COMMERCE_REQUESTS && (
          <Grid xs={12} container alignItems="center">
            <Grid xs={2}>
              <Typography sx={{ fontSize: "12px" }}>گیرنده گزارش:</Typography>
            </Grid>
            <Grid xs={10}>
              <TextField
                id="target"
                size="small"
                label="مثال: معاونت محترم توسعه بازگانی "
                variant="outlined"
                sx={{ width: "100%", height: "100%" }}
                value={formik.values.target}
                error={
                  formik.touched.target ? Boolean(formik.errors.target) : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.target && Boolean(formik.errors.target)
                    ? formik.errors.target
                    : null
                }
              />
            </Grid>
          </Grid>
        )}

        <Grid xs={12} container mt={1}>
          <Grid xs={2}>
            <Typography sx={{ fontSize: "12px" }}>تاریخ گزارش:</Typography>
          </Grid>
          <Grid xs={9}>
            <DatePicker
              label="تاریخ گزارش"
              id="date"
              renderInput={(params) => (
                <TextField size="small" {...params} fullWidth />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid xs={1}>
            <Tooltip title={"رفتن به روز قبل"} placement="bottom">
              <IconButton
                onClick={() => {
                  setSelectedDate1(
                    moment(selectedDate1)
                      .subtract(1, "days")
                      .format("YYYY-MM-DD")
                  );
                }}
                aria-label="delete"
                color="secondary"
              >
                <ArrowBackIcon />
              </IconButton>
            </Tooltip>
          </Grid>
        </Grid>
      </Grid>

      <Grid xs={12} mt={2}>
        <Typography color="red" sx={{ fontSize: "12px", userSelect: "none" }}>
          📌 توجه: بمنظور پرینت صحیح، مشخصه Page size را بر روی A4 تنظیم کنید.
        </Typography>
      </Grid>

      <Button
        disabled={
          pathname !== ROUTE_COMMERCE_REQUESTS ? !formik.isValid : false
        }
        variant="contained"
        onClick={() => {
          setPdfOptions(selectedDate1);
        }}
      >
        پرینت
      </Button>

      <a
        href={`${axios.defaults.baseURL}${
          value === "broadcast"
            ? "daily_process_excel/"
            : "daily_process_klling_proccess_excel"
        }?date=${selectedDate1}&key=${userInfo?.userProfile?.key}`}
        rel="noreferrer"
      >
        <Button color="success" variant="contained">
          خروجی اکسل
        </Button>
      </a>
    </Grid>
  );
}
