import {
  Box,
  Card,
  Grid,
  IconButton,
  Tab,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import {
  ROUTE_PROVINCE_FINANCIAL_FILE,
  ROUTE_SLAUGHTER_FILE,
} from "../../../../routes/routes";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { SPACING } from "../../../../data/spacing";
import { useFormik } from "formik";
import moment from "moment";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch, useSelector } from "react-redux";
import { useContext, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import PlagiarismIcon from "@mui/icons-material/Plagiarism";
import { slaughterGetPayFactorRequestsService } from "../../services/slaughter-get-pay-factor-requests";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import EditIcon from "@mui/icons-material/Edit";
import { SlaughterPayProvinceFactorForm } from "../../../file/components/slaughter-pay-province-factor-form/SlaughterPayProvinceFactorForm";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { slaughterGetPaiedFactorsService } from "../../services/slaughter-get-paied-factors";
import { format } from "date-fns-jalali";
import { formatJustDate } from "../../../../utils/formatTime";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { useReactToPrint } from "react-to-print";
import SlaughterNewFactorFile from "../slaughter-new-factor-file/SlaughterNewFactorFile";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";

export const SlaughterPayFactorRequests = () => {
  const navigate = useNavigate();
  const [dataTable, setDataTable] = useState([]);
  const [paidDataTable, setPaidDataTable] = useState([]);
  const { slaughterGetPayFactorRequests, slaughterGetPaiedFactors } =
    useSelector((state) => state.slaughterSlice);
  const dispatch = useDispatch();

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

  useEffect(() => {
    dispatch(
      slaughterGetPayFactorRequestsService({ selectedDate1, selectedDate2 })
    );
    dispatch(slaughterGetPaiedFactorsService({ selectedDate1, selectedDate2 }));
  }, [selectedDate1, selectedDate2]);

  useEffect(() => {
    const d = slaughterGetPaiedFactors?.map((item, i) => {
      let state = "";
      if (item.state === "accepted") {
        state = "تایید شده";
      } else if (item.state === "rejected") {
        state = "رد شده";
      } else if (item.state === "pending") {
        state = "در انتظار تایید";
      }
      return [
        i + 1,
        item?.provinceFactor?.factorBarCode,
        item?.provinceFactor?.provinceCheckInfo?.killHouseAssignment
          ?.killHouseRequest?.killRequest?.killHouse?.name,
        item?.provinceFactor?.provinceCheckInfo?.killHouseAssignment
          ?.killHouseRequest?.killRequest?.killHouse?.killHouseOperator?.user
          ?.mobile,
        formatJustDate(item?.provinceFactor?.createDate),
        formatJustDate(item?.createDate),
        item?.provinceFactor?.totalPrice?.toLocaleString() + " ﷼",
        Number(item?.paymentCode),
        state,
        <a href={item.factorImage} key="provinceKillRequests">
          <img
            src={item.factorImage}
            width="50"
            height="50"
            alt="بدون بار"
            className="images-file"
          />
        </a>,
        <IconButton
          disabled={item.state === "accepted"}
          key={i}
          color="primary"
          onClick={() => {
            dispatch(
              DRAWER({
                title: "انجام عملیات تایید / رد درخواست",
                // right: !(window.innerWidth <= 600),
                top: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <SlaughterPayProvinceFactorForm
                    key={`SlaughterPayProvinceFactorForm${i}`}
                    factorKey={item.key}
                    price={item?.provinceFactor?.totalPrice}
                    provinceFactorToKillHouse={
                      item?.provinceFactor?.provinceFactorToKillHouse
                    }
                    isRejected={
                      item?.provinceFactor?.killHouseFactorToProvince
                        ?.factorState === "rejected"
                    }
                    killHouseFactorToProvince={
                      item?.provinceFactor?.killHouseFactorToProvince
                    }
                    barCode={
                      item?.provinceFactor?.provinceCheckInfo
                        ?.killHouseAssignment?.killHouseRequest?.barCode
                    }
                  />
                ),
              })
            );
          }}
        >
          <EditIcon />
        </IconButton>,
        <IconButton
          key={i}
          aria-label="delete"
          color="primary"
          onClick={() => {
            navigate(
              ROUTE_PROVINCE_FINANCIAL_FILE +
                item?.provinceFactor?.poultryRequest?.poultryRequestId
            );
          }}
        >
          <PlagiarismIcon />
        </IconButton>,
      ];
    });
    setPaidDataTable(d);
  }, [slaughterGetPaiedFactors]);

  useEffect(() => {
    const d = slaughterGetPayFactorRequests
      ?.filter((item) => item.paidState !== "paid")
      .map((item, i) => {
        const pricePlusDec = `${
          item.provinceInputAmount
            ? item.provinceInputAmount?.toLocaleString()
            : "نامشخص"
        } ﷼ (شرح: ${item?.reason ? item?.reason : "نامشخص"})`;

        let typeOfChangePrice = item.provinceInputAmountType;
        if (typeOfChangePrice === "plus") {
          typeOfChangePrice = (
            <Typography variant="caption">اضافه شد: {pricePlusDec}</Typography>
          );
        } else {
          typeOfChangePrice = (
            <Typography variant="caption">کسر شد: {pricePlusDec}</Typography>
          );
        }

        const firstPayed = (
          <Typography variant="caption">
            کسر شد: {item.killHouseFactorPaymentRemain?.toLocaleString() + " ﷼"}
          </Typography>
        );

        // const totalAmount =
        //   item.provinceCheckInfo.killHouseAssignment.netWeight *
        //   (item.factorFee + item.provinceWage);
        return [
          i + 1,
          item.provinceCheckInfo?.killHouseAssignment?.killHouseRequest
            ?.barCode,
          format(new Date(item?.poultryRequest?.sendDate), "yyyy/MM/dd"),
          `${item.poultryRequest.poultryName} (${item.poultryRequest.poultryUserMobile})`,
          item.provinceFactorToKillHouse.killPlace,
          item.provinceFactorToKillHouse.realQuantity?.toLocaleString(),
          item.provinceFactorToKillHouse.netWeight?.toLocaleString(),
          format(new Date(item?.factorDate), "yyyy/MM/dd"),
          item.provinceFactorToKillHouse.totalFactorAmount?.toLocaleString() +
            " ﷼",
          <Tooltip key={i} title="خروجی PDF">
            <IconButton
              onClick={() => {
                setPdfOptions(item);
              }}
              size={"large"}
              aria-label="delete"
              color="success"
            >
              <PictureAsPdfIcon />
            </IconButton>
          </Tooltip>,
          <IconButton
            key={i}
            color="primary"
            onClick={() => {
              dispatch(
                DRAWER({
                  title: "انجام عملیات پرداخت فاکتور",
                  // right: !(window.innerWidth <= 600),
                  top: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: (
                    <Grid container width="100%">
                      <Grid width="100%">
                        <SimpleTable
                          name="اطلاعات فاکتور"
                          columns={[
                            "کد بار",
                            "تاریخ کشتار",
                            "مرغدار",
                            "محل کشتار",
                            "تعداد واقعی",
                            "وزن خالص بار (کیلوگرم)",
                            "سند بدون بار",
                            "سند با بار",
                          ]}
                          data={[
                            [
                              item.provinceCheckInfo.killHouseAssignment
                                .killHouseRequest.barCode,
                              item?.poultryRequest?.sendDate
                                ? format(
                                    new Date(item?.poultryRequest?.sendDate),
                                    "yyyy/MM/dd"
                                  )
                                : "",
                              `${item.poultryRequest.poultryUserName} (${item.poultryRequest.poultryUserMobile})`,
                              item.provinceFactorToKillHouse.killPlace,
                              item.provinceFactorToKillHouse.realQuantity?.toLocaleString(),
                              item.provinceFactorToKillHouse.netWeight?.toLocaleString() +
                                " کیلوگرم",
                              <a
                                key={"ddd"}
                                href={
                                  item.provinceCheckInfo.killHouseAssignment
                                    .carWeightWithoutLoadImage
                                }
                              >
                                <img
                                  alt="vvv"
                                  width={"50"}
                                  src={
                                    item.provinceCheckInfo.killHouseAssignment
                                      .carWeightWithoutLoadImage
                                  }
                                />
                              </a>,
                              <a
                                key={"ddd"}
                                href={
                                  item.provinceCheckInfo.killHouseAssignment
                                    .carWeightWithLoadImage
                                }
                              >
                                <img
                                  alt="vvv"
                                  width={"50"}
                                  src={
                                    item.provinceCheckInfo.killHouseAssignment
                                      .carWeightWithLoadImage
                                  }
                                />
                              </a>,
                            ],
                          ]}
                        />
                        <SimpleTable
                          name={"اطلاعات فاکتور"}
                          columns={[
                            "قیمت مرغ زنده (کیلوگرم)",
                            "مبلغ خالص بار",
                            "سهم مرغدار",
                            "سهم استان",
                            "هزینه پیامک اطلاع رسانی",
                            "مبلغ کسر/اضافه",
                            "واریزی فاکتور اولیه",
                            "مبلغ فاکتور نهایی",
                          ]}
                          data={[
                            [
                              item.factorFee?.toLocaleString() + " ﷼",
                              item.provinceFactorToKillHouse.realAmountFactor?.toLocaleString() +
                                " ﷼",
                              item.provinceFactorToKillHouse.poultryShare?.toLocaleString() +
                                " ﷼",
                              item.provinceFactorToKillHouse.provinceShare?.toLocaleString() +
                                " ﷼",
                              item.provinceFactorToKillHouse.item
                                ?.provinceCheckInfo?.killHouseAssignment
                                ?.killHouseRequest?.killRequest?.smsPayment
                                ? "دارد - 50000 ﷼"
                                : "ندارد",

                              typeOfChangePrice,
                              firstPayed,
                              item?.totalPrice?.toLocaleString() + " ﷼",
                            ],
                          ]}
                        />
                      </Grid>
                      <SlaughterPayProvinceFactorForm
                        key={`SlaughterPayProvinceFactorForm${i}`}
                        factorKey={item.key}
                        price={item.totalPrice}
                        item={item}
                        provinceFactorToKillHouse={
                          item.provinceFactorToKillHouse
                        }
                        isRejected={
                          item?.killHouseFactorToProvince?.factorState ===
                          "rejected"
                        }
                        killHouseFactorToProvince={
                          item.killHouseFactorToProvince
                        }
                        barCode={
                          item.provinceCheckInfo.killHouseAssignment
                            .killHouseRequest.barCode
                        }
                      />
                    </Grid>
                  ),
                })
              );
            }}
          >
            <EditIcon />
          </IconButton>,
          <IconButton
            key={i}
            aria-label="delete"
            color="primary"
            onClick={() => navigate(ROUTE_SLAUGHTER_FILE + item.poultryReqId)}
          >
            <PlagiarismIcon />
          </IconButton>,
        ];
      });

    setDataTable(d);
  }, [slaughterGetPayFactorRequests]);

  const [tableDataCol] = useState([
    "ردیف",
    "کد بار",
    "تاریخ کشتار",
    "مرغدار",
    "محل کشتار",
    "تعداد واقعی",
    "وزن خالص (کیلوگرم)",
    "تاریخ صدور فاکتور",
    "مبلغ نهایی فاکتور",
    "دانلود فاکتور",
    "عملیات",
    "مشاهده",
  ]);

  const formik = useFormik({
    initialValues: {
      capacity: "",
      recieveTime: "",
      recieveDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
    },
    validationSchema: Yup.object({
      capacity: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      recieveTime: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
    }),
  });

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

  const [value, setValue] = useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const [data, setData] = useState();
  const componentRef = useRef();
  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: "فاکتور پرداخت",
    onAfterPrint: () => {
      setData(null);
    },
  });

  const setPdfOptions = (item) => {
    setData(item);
  };

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

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="center"
      gap={SPACING.SMALL}
      mt={SPACING.MEDIUM}
    >
      <div style={{ visibility: "hidden", position: "absolute" }}>
        <SlaughterNewFactorFile ref={componentRef} item={data} />
      </div>

      <Grid>
        <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
          <Tabs
            value={value}
            onChange={handleChange}
            aria-label="basic tabs example"
          >
            <Tab label="فاکتور های جدید" />
            <Tab label="فاکتورهای پرداخت شده" />
          </Tabs>
        </Box>
      </Grid>
      <Card sx={{ width: "100%" }}>
        {value === 0 && (
          <AdvancedTable
            name={
              <Grid container alignItems="center" gap={SPACING.SMALL}>
                <Grid xs={12} sm={12} md={12} lg={2}>
                  <Typography>فاکتورهای در انتظار پرداخت</Typography>
                </Grid>
                <Grid>
                  <DatePicker
                    label="از تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate1}
                    onChange={(e) => {
                      setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    label="تا تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
              </Grid>
            }
            columns={tableDataCol}
            data={dataTable}
          />
        )}

        {value === 1 && (
          <AdvancedTable
            name={
              <Grid container alignItems="center" gap={SPACING.SMALL}>
                <Grid xs={12} sm={12} md={12} lg={2}>
                  <Typography>فاکتورهای پرداخت شده</Typography>
                </Grid>
                <Grid>
                  <DatePicker
                    label="از تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate1}
                    onChange={(e) => {
                      setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    label="تا تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
              </Grid>
            }
            columns={[
              "ردیف",
              "شناسه فاکتور",
              "کشتارگاه",
              "تلفن کشتارگاه",
              "تاریخ صدور فاکتور",
              "تاریخ پرداخت فاکتور",
              "مبلغ فاکتور نهایی",
              "شناسه پرداخت",
              "وضعیت",
              "سند پرداختی",
              "ویرایش سند پرداخت",
              "مشاهده",
            ]}
            data={paidDataTable}
          />
        )}
      </Card>
    </Grid>
  );
};
