import moment from "moment";
import React, { useEffect, useState, useContext, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useReactToPrint } from "react-to-print";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import { BsFillFileEarmarkPdfFill } from "react-icons/bs";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { provinceGetContradictionsData } from "../../services/provinceGetContradictionsData";

import { Accordion, AccordionDetails, AccordionSummary } from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ProvinceGetContradictionsFile from "../province-get-contradictions-file/ProvinceGetContradictionsFile";
import {
  TablePage1Part2Web,
  TablePage1Web,
  TablePage2Web,
  TablePage3Web,
  TablePage4Web,
  TablePage5Web,
} from "../province-get-contradictions-file/PagesWeb";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const ProvinceManageContradictions = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [data, setData] = useState();
  const [dataTable, setDataTable] = useState();

  const dispatch = useDispatch();

  const componentRef = useRef();
  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: `گزارش مغایرت درخواست کشتار و عدم فعالیت نقش ها `,
  });

  const handleSubmit = () => {
    dispatch(LOADING_START());
    dispatch(
      provinceGetContradictionsData({ selectedDate1, selectedDate2 })
    ).then((r) => {
      setDataTable(r.payload.data);
      dispatch(LOADING_END());
    });
  };
  const userInfo = useSelector((state) => state.userSlice);

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

  useEffect(() => {
    const fetchData = () => {
      const currentDate = moment(new Date()).format("YYYY-MM-DD");
      const newSelectedDate1 = moment(currentDate)
        .subtract(1, "days")
        .format("YYYY-MM-DD");
      const newSelectedDate2 = currentDate;

      setSelectedDate1(newSelectedDate1);
      setSelectedDate2(newSelectedDate2);

      dispatch(LOADING_START());
      try {
        const response = dispatch(
          provinceGetContradictionsData({
            selectedDate1: newSelectedDate1,
            selectedDate2: newSelectedDate2,
          })
        );
        setDataTable(response.payload.data);
      } catch (error) {
        dispatch(LOADING_END());
      }
    };

    fetchData();
  }, []);

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

  return (
    <Grid container p={SPACING.TINY} xs={12}>
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <div style={{ visibility: "hidden", position: "absolute" }}>
          <ProvinceGetContradictionsFile
            ref={componentRef}
            item={data}
            inDate1={selectedDate1}
            inDate2={selectedDate2}
          />
        </div>
        <Typography variant="body2">
          دریافت لیست مغایرت ها (حداکثر بازه 7 روزه)
        </Typography>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Button
          disabled={
            moment(selectedDate2).diff(moment(selectedDate1), "days") > 7
          }
          type="submit"
          onClick={handleSubmit}
          endIcon={<RiSearchLine />}
        >
          جستجو
        </Button>
        <Tooltip title="خروجی PDF">
          <IconButton
            disabled={
              moment(selectedDate2).diff(moment(selectedDate1), "days") > 7
            }
            aria-label="delete"
            color="success"
            onClick={() => {
              setPdfOptions(selectedDate1);
            }}
          >
            <BsFillFileEarmarkPdfFill size={28} />
          </IconButton>
        </Tooltip>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }discrepancy_report_excel/?date1=${selectedDate1}&date2=${selectedDate2}&key=${
              userInfo?.userProfile?.key
            }&role=${getRoleFromUrl()}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>
      {dataTable && (
        <Grid width="100%" mt={SPACING.SMALL}>
          {dataTable && (
            <Grid width="100%" mt={SPACING.SMALL}>
              {renderAccordion(
                "درخواست کشتار و تخصیص",
                <TablePage1Web item={dataTable?.partOne} />
              )}
              {renderAccordion(
                "مغایرت در ثبت ماشین و ایجاد بار",
                <TablePage1Part2Web
                  items={dataTable?.partTwo}
                  start={1}
                  end={1000}
                />
              )}
              {renderAccordion(
                "بارهای دارای مغایرت تعداد",
                <TablePage2Web
                  items={dataTable?.partSeven}
                  start={1}
                  end={1000}
                />
              )}
              {renderAccordion(
                "بارهای فاقد کد قرنطینه",
                <TablePage2Web
                  items={dataTable?.partThree}
                  start={1}
                  end={1000}
                />
              )}
              {renderAccordion(
                "بارهای تخلیه نشده",
                <TablePage3Web
                  items={dataTable?.partFour}
                  start={1}
                  end={1000}
                />
              )}
              {renderAccordion(
                "بارهاي تکمیل نشده (بارگزاري سند باسکول و مستندات وزنی)",
                <TablePage4Web
                  items={dataTable?.partFive}
                  start={1}
                  end={1000}
                />
              )}
              {renderAccordion(
                "مغایرت در اطلاعات بار",
                <TablePage5Web
                  items={dataTable?.partSix}
                  start={1}
                  end={1000}
                />
              )}
            </Grid>
          )}
        </Grid>
      )}
    </Grid>
  );
};

const renderAccordion = (label, content) => (
  <Accordion>
    <AccordionSummary
      expandIcon={<ExpandMoreIcon />}
      aria-controls="panel-content"
      id="panel-header"
    >
      <Typography variant="subtitle1">{label}</Typography>
    </AccordionSummary>
    <AccordionDetails>{content}</AccordionDetails>
  </Accordion>
);
