import { IconButton, Typography } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
// import PrintIcon from "@mui/icons-material/Print";
import { PropTypes } from "prop-types";
// import { FactorToPrint } from "../factor-to-print/FactorToPrint";
import { formatTime } from "../../../../utils/formatTime";
import {
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import NoteAddIcon from "@mui/icons-material/NoteAdd";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { FactorPaymentShareDrawer } from "../../../file/components/factor-payment-share-drawer/FactorPaymentShareDrawer";
import { useDispatch } from "react-redux";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import useRequestFile from "../../../file/hooks/useRequestFile";
// import { useRef } from "react";
// import ReactToPrint from "react-to-print";

export const Factor = ({ process, id }) => {
  const dispatch = useDispatch();
  const myFile = useRequestFile(id);
  process = process ? process : myFile?.file?.process;

  // const slaughterAllocatedRequests = useSlaughterAllocatedRequests(id);
  // const { id } = useParams();
  // const componentRef = useRef();
  // const handlePrint = () => {
  // var printWindow = window.open(FactorToPrint);
  // printWindow.print();
  // };
  let provinceShare,
    cityShare,
    fanavaShare,
    companyShare,
    unionShare,
    poultryShare;

  const isProvinceSubmitDocEnabled =
    getRoleFromUrl() === "ProvinceFinancial" &&
    !process.allocation?.provincePaymentDocuments?.length &&
    !!process.allocation?.provinceShareRemaining;
  const isFanavaSubmitDocEnabled =
    getRoleFromUrl() === "ProvinceFinancial" &&
    !process.allocation?.fanavaPaymentDocuments?.length &&
    !!process.allocation?.fanavaShareRemaining;
  const isCitySubmitDocEnabled =
    getRoleFromUrl() === "ProvinceFinancial" &&
    !process.allocation?.cityPaymentDocuments?.length &&
    !!process.allocation?.cityShareRemaining;
  const isCompanySubmitDocEnabled =
    getRoleFromUrl() === "ProvinceFinancial" &&
    !process.allocation?.companyPaymentDocuments?.length &&
    !!process.allocation?.companyShareRemaining;
  const isCentralUnionSubmitDocEnabled =
    getRoleFromUrl() === "ProvinceFinancial" &&
    !process.allocation?.centralUnionPaymentDocuments?.length &&
    !!process.allocation?.centralUnionShareRemaining;
  const isPoultrySubmitDocEnabled =
    getRoleFromUrl() === "ProvinceFinancial" &&
    !process.allocation?.poultryPaymentDocuments?.length &&
    !!process.allocation?.poultryRemaining;

  if (process.allocation?.provinceShareDigit) {
    provinceShare = [
      `سهم اتحادیه`,
      process.allocation?.provinceCardNumber,
      process.allocation?.provinceShaba,
      process.allocation?.provinceBankInfo,
      process.allocation?.provinceShareDigit + " ریال",
      process.allocation?.provinceSharePayment + " ریال",
      process.allocation?.provinceShareRemaining + " ریال",
      process.allocation?.provincePaymentDocuments?.map((doc, i) => {
        return (
          <a key={"document" + i} href={doc.image}>
            <img
              alt="document"
              width="40"
              height="40"
              src={doc.image}
              style={{ borderRadius: "5px" }}
            />
          </a>
        );
      }),
      <IconButton
        key="fff"
        color="primary"
        component="label"
        disabled={!isProvinceSubmitDocEnabled}
        onClick={() => {
          dispatch(
            OPEN_MODAL({
              title: "ثبت سند مالی",
              content: (
                <FactorPaymentShareDrawer
                  fileId={id}
                  allocationKey={process.allocation?.allocationKey}
                  paymentPrice={process.allocation?.provinceShareRemaining}
                  share={"ProvinceOperator"}
                />
              ),
            })
          );
        }}
      >
        <NoteAddIcon />
      </IconButton>,
    ];
  }

  if (process.allocation?.fanavaShareDigit) {
    fanavaShare = [
      `سهم فن آوا`,
      process.allocation?.fanavaCardNumber,
      process.allocation?.fanavaShaba,
      process.allocation?.fanavaBankInfo,
      process.allocation?.fanavaShareDigit + " ریال",
      process.allocation?.fanavaSharePayment + " ریال",
      process.allocation?.fanavaShareRemaining + " ریال",
      process.allocation?.fanavaPaymentDocuments?.map((doc, i) => {
        return (
          <a key={"fanavaPaymentDocuments" + i} href={doc.image}>
            <img
              alt="document"
              width="40"
              height="40"
              src={doc.image}
              style={{ borderRadius: "5px" }}
            />
          </a>
        );
      }),
      <IconButton
        key="fff"
        color="primary"
        component="label"
        disabled={!isFanavaSubmitDocEnabled}
        onClick={() => {
          dispatch(
            DRAWER({
              right: true,
              title: "ثبت سند مالی",
              content: (
                <FactorPaymentShareDrawer
                  share={"fanava"}
                  fileId={id}
                  paymentPrice={process.allocation?.fanavaShareRemaining}
                  allocationKey={process.allocation?.allocationKey}
                />
              ),
            })
          );
        }}
      >
        <NoteAddIcon />
      </IconButton>,
    ];
  }

  if (process.allocation?.cityShareDigit) {
    cityShare = [
      `سهم شهرستان`,
      process.allocation?.cityCardNumber,
      process.allocation?.cityShaba,
      process.allocation?.cityBankInfo,
      process.allocation?.cityShareDigit + " ریال",
      process.allocation?.citySharePayment + " ریال",
      process.allocation?.cityShareRemaining + " ریال",
      process.allocation?.cityPaymentDocuments?.map((doc, i) => {
        return (
          <a key={"cityPaymentDocuments" + i} href={doc.image}>
            <img
              alt="document"
              width="40"
              height="40"
              src={doc.image}
              style={{ borderRadius: "5px" }}
            />
          </a>
        );
      }),
      <IconButton
        key="fff"
        color="primary"
        component="label"
        disabled={!isCitySubmitDocEnabled}
        onClick={() => {
          dispatch(
            OPEN_MODAL({
              title: "ثبت سند مالی",
              content: (
                <FactorPaymentShareDrawer
                  share={"CityOperator"}
                  fileId={id}
                  paymentPrice={process.allocation?.cityShareRemaining}
                  allocationKey={process.allocation?.allocationKey}
                />
              ),
            })
          );
        }}
      >
        <NoteAddIcon />
      </IconButton>,
    ];
  }

  if (process.allocation?.companyShareDigit) {
    companyShare = [
      `سهم شرکت`,
      process.allocation?.companyCardNumber,
      process.allocation?.companyShaba,
      process.allocation?.companyBankInfo,
      process.allocation?.companyShareDigit + " ریال",
      process.allocation?.companySharePayment + " ریال",
      process.allocation?.companyShareRemaining + " ریال",
      process.allocation?.companyPaymentDocuments?.map((doc, i) => {
        return (
          <a key={"companyPaymentDocuments" + i} href={doc.image}>
            <img
              alt="document"
              width="40"
              height="40"
              src={doc.image}
              style={{ borderRadius: "5px" }}
            />
          </a>
        );
      }),
      <IconButton
        key="fff"
        color="primary"
        component="label"
        disabled={!isCompanySubmitDocEnabled}
        onClick={() => {
          dispatch(
            OPEN_MODAL({
              right: true,
              title: "ثبت سند مالی",
              content: (
                <FactorPaymentShareDrawer
                  share={"company"}
                  fileId={id}
                  paymentPrice={process.allocation?.companyShareRemaining}
                  allocationKey={process.allocation?.allocationKey}
                />
              ),
            })
          );
        }}
      >
        <NoteAddIcon />
      </IconButton>,
    ];
  }

  if (process.allocation?.centralUnionShareDigit) {
    unionShare = [
      `سهم اتحادیه مرکزی`,
      process.allocation?.centralUnionCardNumber,
      process.allocation?.centralUnionShaba,
      process.allocation?.centralUnionBankInfo,
      process.allocation?.centralUnionShareDigit + " ریال",
      process.allocation?.centralUnionSharePayment + " ریال",
      process.allocation?.centralUnionShareRemaining + " ریال",
      process.allocation?.centralUnionPaymentDocuments?.map((doc, i) => {
        return (
          <a key={"centralUnionPaymentDocuments" + i} href={doc.image}>
            <img
              alt="document"
              width="40"
              height="40"
              src={doc.image}
              style={{ borderRadius: "5px" }}
            />
          </a>
        );
      }),
      <IconButton
        key="fff"
        color="primary"
        component="label"
        disabled={!isCentralUnionSubmitDocEnabled}
        onClick={() => {
          dispatch(
            OPEN_MODAL({
              title: "ثبت سند مالی",
              content: (
                <FactorPaymentShareDrawer
                  share={"central"}
                  fileId={id}
                  paymentPrice={process.allocation?.centralUnionShareRemaining}
                  allocationKey={process.allocation?.allocationKey}
                />
              ),
            })
          );
        }}
      >
        <NoteAddIcon />
      </IconButton>,
    ];
  }

  if (process.allocation?.poultryShareDigit) {
    poultryShare = [
      `سهم مرغدار`,
      process.allocation?.poultryCardNumber,
      process.allocation?.poultryShaba,
      process.allocation?.poultryBankInfo,
      process.allocation?.poultryShareDigit + " ریال",
      process.allocation?.poultrySharePayment + " ریال",
      process.allocation?.poultryRemaining + " ریال",
      process.allocation?.poultryPaymentDocuments?.map((doc, i) => {
        return (
          <a key={"poultryPaymentDocuments" + i} href={doc.image}>
            <img
              alt="document"
              width="40"
              height="40"
              src={doc.image}
              style={{ borderRadius: "5px" }}
            />
          </a>
        );
      }),
      <IconButton
        key="fff"
        color="primary"
        component="label"
        disabled={!isPoultrySubmitDocEnabled}
        onClick={() => {
          dispatch(
            OPEN_MODAL({
              title: "ثبت سند مالی",
              content: (
                <FactorPaymentShareDrawer
                  share={"Poultry"}
                  fileId={id}
                  paymentPrice={process.allocation?.poultryRemaining}
                  allocationKey={process.allocation?.allocationKey}
                />
              ),
            })
          );
        }}
      >
        <NoteAddIcon />
      </IconButton>,
    ];
  }

  const factorTableData = [
    provinceShare,
    cityShare,
    fanavaShare,
    companyShare,
    unionShare,
    poultryShare,
  ].filter((item) => !!item);

  return (
    <>
      <TimelineItem sx={{ alignSelf: "flex-start", width: "100%" }}>
        <TimelineSeparator>
          <TimelineDot />
          <TimelineConnector />
        </TimelineSeparator>
        <Grid container direction="column" flexWrap="nowrap" flex="1">
          <Grid container alignItems="flex-start">
            <Grid>
              <TimelineOppositeContent>
                <Typography variant="body1" fontWeight="bold">
                  فاکتور نهایی
                </Typography>
              </TimelineOppositeContent>
            </Grid>
            <Grid>
              <TimelineContent color="textSecondary">
                <Grid
                  container
                  direction="row"
                  justifyContent="space-between"
                  alignItems="center"
                  gap={SPACING.SMALL}
                >
                  <Typography
                    variant="body2"
                    display="flex"
                    gap={SPACING.SMALL}
                  >
                    ﺷﻤﺎﺭﻩ ﻓﺎﮐﺘﻮﺭ:
                  </Typography>
                  <Typography variant="body2" fontWeight="bold">
                    {process?.poultry?.poultryOrderCode}
                  </Typography>
                  <Typography
                    variant="body2"
                    display="flex"
                    gap={SPACING.SMALL}
                  >
                    تاریخ:
                  </Typography>
                  <Typography variant="body2" fontWeight="bold">
                    {formatTime(process?.poultry?.poultrySendDate)}
                  </Typography>

                  {/* <Grid>
                    <ReactToPrint
                      trigger={() => (
                        <Button
                          onClick={handlePrint}
                          style={{ flex: 1 }}
                          size="small"
                          endIcon={<PrintIcon />}
                          variant="contained"
                        >
                          دانلود فاکتور
                        </Button>
                      )}
                      content={() => componentRef.current}
                    />
                    <FactorToPrint process={process} ref={componentRef} />
                  </Grid> */}
                </Grid>
              </TimelineContent>
            </Grid>
          </Grid>
          <Grid container mt={SPACING.SMALL} spacing={SPACING.TINY}>
            <Grid width="100%">
              <Grid>
                <SimpleTable
                  columns={[
                    "اطلاعات مالی",
                    "شماره کارت",
                    "شبا",
                    "صاحب حساب",
                    "جمع کل",
                    "جمع پرداختی",
                    "مانده",
                    "اسناد",
                    "ثبت",
                  ]}
                  data={factorTableData}
                />
                {process.allocation?.totalMoney && (
                  <SimpleTable
                    columns={["مبلغ کل به عدد", "مبلغ کل به حروف"]}
                    data={[
                      [
                        process.allocation?.totalMoney?.toLocaleString() +
                          " ریال",
                        process.allocation?.totalMoneyChar,
                      ],
                    ]}
                  />
                )}
              </Grid>
            </Grid>
            {/* <Grid>
              {process.allocation?.provinceShareChar && (
                <Grid
                  container
                  gap={SPACING.SMALL}
                  margin={SPACING.SMALL}
                  alignItems="center"
                >
                  <CircleIcon color="primary" fontSize="small" />
                  <Typography>
                    سهم اتحادیه:{" "}
                    {process.allocation?.provinceShareDigit.toLocaleString() +
                      " ریال"}{" "}
                    ({process.allocation?.provinceShareChar})
                  </Typography>
                </Grid>
              )}
              {process.allocation?.cityShareChar && (
                <Grid
                  container
                  gap={SPACING.SMALL}
                  margin={SPACING.SMALL}
                  alignItems="center"
                >
                  <CircleIcon color="primary" fontSize="small" />
                  <Typography>
                    سهم شهرستان:{" "}
                    {process.allocation?.cityShareDigit.toLocaleString() +
                      " ریال"}{" "}
                    ({process.allocation?.cityShareChar})
                  </Typography>
                </Grid>
              )}
              {process.allocation?.fanavaShareShareChar && (
                <Grid
                  container
                  gap={SPACING.SMALL}
                  margin={SPACING.SMALL}
                  alignItems="center"
                >
                  <CircleIcon color="primary" fontSize="small" />
                  <Typography>
                    سهم فن آوا:{" "}
                    {process.allocation?.fanavaShareDigit.toLocaleString() +
                      " ریال"}{" "}
                    ({process.allocation?.fanavaShareShareChar})
                  </Typography>
                </Grid>
              )}
              {process.allocation?.companyShareChar && (
                <Grid
                  container
                  gap={SPACING.SMALL}
                  margin={SPACING.SMALL}
                  alignItems="center"
                >
                  <CircleIcon color="primary" fontSize="small" />
                  <Typography>
                    سهم شرکت:{" "}
                    {process.allocation?.companyShareDigit.toLocaleString() +
                      " ریال"}{" "}
                    ({process.allocation?.companyShareChar})
                  </Typography>
                </Grid>
              )}

              {process.allocation?.centralUnionShareChar && (
                <Grid
                  container
                  gap={SPACING.SMALL}
                  margin={SPACING.SMALL}
                  alignItems="center"
                >
                  <CircleIcon color="primary" fontSize="small" />
                  <Typography>
                    سهم اتحادیه مرکزی:{" "}
                    {process.allocation?.centralUnionShareDigit.toLocaleString() +
                      " ریال"}{" "}
                    ({process.allocation?.centralUnionShareChar})
                  </Typography>
                </Grid>
              )}
              {process.allocation?.poultryShareChar && (
                <Grid
                  container
                  gap={SPACING.SMALL}
                  margin={SPACING.SMALL}
                  alignItems="center"
                >
                  <CircleIcon color="primary" fontSize="small" />
                  <Typography>
                    پرداختی مرغدار:{" "}
                    {process.allocation?.poultryShareDigit.toLocaleString() +
                      " ریال"}{" "}
                    ({process.allocation?.poultryShareChar})
                  </Typography>
                </Grid>
              )}
              {process.allocation?.totalMoneyChar && (
                <Grid
                  container
                  gap={SPACING.SMALL}
                  margin={SPACING.SMALL}
                  alignItems="center"
                >
                  <CircleIcon color="primary" fontSize="small" />
                  <Typography>
                    مبلغ کل:{" "}
                    {process.allocation?.totalMoney.toLocaleString() + " ریال"}{" "}
                    ({process.allocation?.totalMoneyChar})
                  </Typography>
                </Grid>
              )}
            </Grid> */}
          </Grid>
        </Grid>
        {/* <FactorToPrint process={process} /> */}
      </TimelineItem>
    </>
  );
};

Factor.propTypes = {
  process: PropTypes.any,
};
