import {
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { Typography } from "@mui/material";
import React, { useEffect } from "react";
import { PropTypes } from "prop-types";
import { Grid } from "../../../../components/grid/Grid";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { SPACING } from "../../../../data/spacing";
import { formatTime } from "../../../../utils/formatTime";
import moment from "moment";
import { Timer } from "../../../../components/timer/Timer";
import { useDispatch, useSelector } from "react-redux";
import { avicultureGetChickenPrice } from "../../../aviculture/services/aviculture-get-chicken-price";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
// import { useSelector } from "react-redux";

const FinancialCheckRequestInformation = ({ data, auction }) => {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(avicultureGetChickenPrice());
  }, []);
  // let columns = [];
  // let item = [];

  const { avicultureChickenPrice } = useSelector(
    (state) => state.avicultureSlice
  );

  const liveChickenPrice = avicultureChickenPrice?.liveChickenPrice;

  let barInfoColumns,
    barInfoData,
    financialColumns,
    financialColumnsCash,
    financialData,
    financialDataCash;
  const paymentDate = moment(new Date(data.paymentDeadLine));
  const currentDate = moment();
  const diff = paymentDate.diff(currentDate);
  let paymentRemainedSeconds = moment.duration(diff).asSeconds();
  if (auction) {
    // columns = [
    //   "کشتارگاه",
    //   "تعداد",
    //   "نام راننده",
    //   "ماشین",
    //   "وزن بار",
    //   "سند خودرو بدون بار",
    //   "سند خودرو با بار",
    //   "وضعیت",
    // ];
    // item = [
    //   [
    //     data.quantity + " قطعه",
    //     data.cars.driverName + ` (${data.cars.driverMobile})`,
    //     `${data.cars.typeCar} با پلاک ${data.cars.pelak}`,
    //     data.barInfo.killHouseNetWeight + " کیلوگرم",
    //     data.barInfo.killHouseNetWeight + " کیلوگرم",
    //     <a
    //       href={data.barInfo.killHouseImageWithoutLoad}
    //       alt="دانلود سند خودرو بدون بار"
    //       key="provinceKillRequests"
    //     >
    //       <img
    //         src={data.barInfo.killHouseImageWithoutLoad}
    //         width="50"
    //         height="50"
    //         alt="بدون بار"
    //         className="images-file"
    //       />
    //     </a>,
    //     <a
    //       href={data.barInfo.killHouseImageWithLoad}
    //       alt="دانلود سند خودرو با بار"
    //       key="provinceKillRequests"
    //     >
    //       <img
    //         src={data.barInfo.killHouseImageWithLoad}
    //         width="50"
    //         height="50"
    //         alt="بدون بار"
    //         className="images-file"
    //         key="provinceKillRequests"
    //       />
    //     </a>,
    //     !data.killHouseFactorToProvince && data.provinceFactorToKillHouse
    //       ? "در انتظار پرداخت کشتارگاه"
    //       : "پرداخت شده توسط کشتارگاه",
    //   ],
    // ];
  } else {
    let state;
    state =
      !data.killHouseFactorToProvince && !data.provinceFactorToKillHouse
        ? "در انتظار تایید مالی"
        : state;
    state =
      !data.killHouseFactorToProvince && data.provinceFactorToKillHouse
        ? "در انتظار پرداخت کشتارگاه"
        : state;
    state =
      data.killHouseFactorToProvince && data.provinceFactorToKillHouse
        ? "پرداخت شده توسط کشتارگاه"
        : state;

    let timerState;
    const isFactorPayed =
      data.killHouseFactorToProvince?.factorState === "accepted" ||
      data.killHouseFactorToPoultry?.factorState === "accepted";

    const timer = data && (
      <Timer
        key="finincalTimer"
        isFilePaymentTime={true}
        seconds={paymentRemainedSeconds}
      />
    );
    const isPaymentFactorPending =
      !data.killHouseFactorToProvince &&
      !data.provinceFactorToKillHouseForPoultry;

    const isPaymentPendingAndTimerEnabled = Boolean(data.paymentDeadLine);

    // if (
    //   !data.provinceFactorToKillHouse ||
    //   !data.provinceFactorToKillHouseForPoultry
    // ) {
    //   timerState = "در انتظار تایید مالی";
    // } else if (isFactorPayed) {
    //   timerState = "پرداخت شده ✔";
    // } else if (isPaymentPendingAndTimerEnabled) {
    //   timerState = timer;
    // } else if (isPaymentPending) {
    //   timerState = "در انتظار صدور تمامی فاکتورها";
    // }

    if (isPaymentPendingAndTimerEnabled) {
      timerState = timer;
    } else if (isPaymentFactorPending) {
      timerState = "در انتظار تایید مالی";
    } else {
      timerState = "در انتظار صدور تمامی فاکتورها";
    }
    if (isFactorPayed) {
      timerState = "پرداخت شده ✔";
    }

    barInfoColumns = [
      "کشتارگاه",
      "نام راننده",
      "ماشین",
      // "کد قرنطینه",
      // "کد حمل و نقل",
      "نوع خرید",
      "سند خودرو بدون بار",
      "سند خودرو با بار",
      "تعداد درخواست",
      "تعداد واقعی بارگیری",
      "وزن بار",
      "میانگین وزن",
    ];

    barInfoData = [
      [
        `${data.killHouseName} (${data.killHouseUserProvince}/${data.killHouseUserCity})`,
        data.cars?.driverName + ` (${data.cars?.driverMobile})`,
        `${data.cars?.typeCar} با پلاک ${data.cars?.pelak}`,
        `${data.paymentType === "credit" ? "زمان دار" : "نقدی"}`,
        <a
          style={{ textDecoration: "none", color: "black" }}
          href={data.barInfo.killHouseImageWithoutLoad}
          alt="دانلود سند خودرو بدون بار"
          key="provinceKillRequests"
        >
          <img
            src={data.barInfo.killHouseImageWithoutLoad}
            width="50"
            height="50"
            alt="بدون بار"
            className="images-file"
          />
          <p>{data.barInfo.killHouseWeightWithoutLoad} کیلوگرم</p>
        </a>,
        <a
          style={{ textDecoration: "none", color: "black" }}
          href={data.barInfo.killHouseImageWithLoad}
          alt="دانلود سند خودرو با بار"
          key="provinceKillRequests"
        >
          <img
            src={data.barInfo.killHouseImageWithLoad}
            width="50"
            height="50"
            alt="بدون بار"
            className="images-file"
            key="provinceKillRequests"
          />
          <p>{data.barInfo.killHouseWeightWithLoad} کیلوگرم</p>
        </a>,
        data.quantity + " قطعه",
        data.barInfo.realQuantity + " قطعه",
        data.barInfo.killHouseNetWeight + " کیلوگرم",
        (data.barInfo.killHouseNetWeight / data.barInfo.realQuantity).toFixed(
          2
        ) + " کیلوگرم",
      ],
    ];
    financialColumns = [
      "قیمت روز",
      "قیمت هرکیلو",
      "سهم مرغدار",
      "سهم اتحادیه",
      "مانده تا سررسید 30 روزه",
      "سهم مرغدار با ضریب سود",
      "سهم اتحادیه با ضریب سود",
      "جمع مبلغ قابل پرداخت",
      "وضعیت",
    ];

    let poultryShareWithProfit;
    if (data.provinceFactorToKillHouse?.poultryShareWithProfit) {
      poultryShareWithProfit =
        data.provinceFactorToKillHouse?.poultryShareWithProfit;
    } else if (
      data.provinceFactorToKillHouseForPoultry?.poultryShareWithProfit
    ) {
      poultryShareWithProfit =
        data.provinceFactorToKillHouseForPoultry?.poultryShareWithProfit;
    }
    financialData = [
      [
        liveChickenPrice + " ﷼",
        data.provinceFactorToKillHouse
          ? data.provinceFactorToKillHouse.provinceFactorFee + " ریال"
          : "نامشخص",
        data.provinceFactorToKillHouse
          ? data.provinceFactorToKillHouse.provinceFactorFee *
              data.barInfo.killHouseNetWeight +
            " ریال"
          : "نامشخص",
        data.provinceFactorToKillHouse?.totalShareAllocation
          ? data.provinceFactorToKillHouse?.totalShareAllocation + " ریال"
          : "نامشخص",
        timerState,
        poultryShareWithProfit ? `${poultryShareWithProfit} ریال` : "نامشخص",
        data.provinceFactorToKillHouse?.unionShareWithProfit
          ? `${data.provinceFactorToKillHouse?.unionShareWithProfit} ریال`
          : "نامشخص",
        data.provinceFactorToKillHouse?.cost
          ? `${
              data.provinceFactorToKillHouse?.cost +
              data.provinceFactorToKillHouse?.poultryShareWithProfit
            } ریال`
          : "نامشخص",
        state,
      ],
    ];

    financialColumnsCash = [
      "قیمت روز",
      "قیمت هرکیلو",
      "سهم مرغدار",
      "سهم اتحادیه",
      "مبلغ قابل پرداخت",
      "وضعیت",
    ];

    let pricePayment;
    if (data.provinceFactorToKillHouse?.cost) {
      pricePayment = `${data.provinceFactorToKillHouse?.cost} ریال`;
    } else if (data.provinceFactorToKillHouseForPoultry?.cost) {
      pricePayment = `${data.provinceFactorToKillHouseForPoultry?.cost} ریال`;
    } else {
      pricePayment = "نامشخص";
    }

    financialDataCash = [
      [
        liveChickenPrice + " ﷼",
        data.provinceFactorToKillHouse
          ? data.provinceFactorToKillHouse.provinceFactorFee + " ریال"
          : "ندارد",
        // data.provinceFactorToKillHouse
        //   ? data.provinceFactorToKillHouse.provinceFactorFee *
        //       data.barInfo.killHouseNetWeight +
        //     " ریال"
        //   : "ندارد",
        poultryShareWithProfit ? `${poultryShareWithProfit} ریال` : "نامشخص",
        data.provinceFactorToKillHouse?.totalShareAllocation
          ? data.provinceFactorToKillHouse?.totalShareAllocation + " ریال"
          : "نامشخص",
        pricePayment,
        state,
      ],
    ];

    // remove payment fields for aviculture
    const urlRole = getRoleFromUrl();
    if (urlRole === "Poultry") {
      financialColumnsCash.splice(5, 3);
      financialDataCash[0]?.splice(5, 3);

      financialColumns.splice(5, 4);
      financialData[0]?.splice(5, 4);
    }
  }
  return (
    <TimelineItem sx={{ alignSelf: "flex-start", width: "100%" }}>
      <TimelineSeparator>
        <TimelineDot />
        <TimelineConnector />
      </TimelineSeparator>
      <Grid container direction="column" flexWrap="nowrap" flex="1">
        <Grid container>
          <Grid>
            <TimelineOppositeContent>
              <Typography variant="body1" fontWeight="bold">
                مرحله مالی
              </Typography>
            </TimelineOppositeContent>
          </Grid>
          <Grid>
            <TimelineContent color="textSecondary">
              <Grid container gap={SPACING.SMALL}>
                {data.barInfo.killHouseAssignmentState === "pending" ? (
                  <Typography
                    variant="body2"
                    display="flex"
                    gap={SPACING.SMALL}
                  >
                    درخواست در انتظار تایید اپراتور مالی است.
                  </Typography>
                ) : (
                  <>
                    <Typography
                      variant="body2"
                      display="flex"
                      gap={SPACING.SMALL}
                    >
                      درخواست در تاریخ
                    </Typography>
                    <Typography variant="body2" fontWeight="bold">
                      {formatTime(new Date(data.barInfo.acceptRejectDate))}
                    </Typography>
                    <Typography
                      variant="body2"
                      display="flex"
                      gap={SPACING.SMALL}
                    >
                      {data.barInfo.killHouseAssignmentState === "accepted"
                        ? "تایید شده است."
                        : data.barInfo.killHouseAssignmentState === "pending"
                        ? "در انتظار تایید"
                        : "رد شده است."}
                    </Typography>
                  </>
                )}
              </Grid>
            </TimelineContent>
          </Grid>
        </Grid>
        <Grid container>
          <Grid xs={12}>
            <SimpleTable
              name={`اطلاعات بار ${data.barcod} - کد قرنطینه ${data.clearanceCode} - کد حمل و نقل ${data.trafficCode}`}
              columns={barInfoColumns}
              data={barInfoData}
            />
            {data.paymentType === "cash" ? (
              <SimpleTable
                name="اطلاعات مالی"
                columns={financialColumnsCash}
                data={financialDataCash}
              />
            ) : (
              <SimpleTable
                name="اطلاعات مالی"
                columns={financialColumns}
                data={financialData}
              />
            )}
          </Grid>
        </Grid>
      </Grid>
    </TimelineItem>
  );
};
FinancialCheckRequestInformation.propTypes = {
  item: PropTypes.array,
  data: PropTypes.any,
  auction: PropTypes.bool,
};

export default FinancialCheckRequestInformation;
