import Timeline from "@mui/lab/Timeline";
import TimelineItem from "@mui/lab/TimelineItem";
import TimelineSeparator from "@mui/lab/TimelineSeparator";
import TimelineConnector from "@mui/lab/TimelineConnector";
import TimelineContent from "@mui/lab/TimelineContent";
import TimelineDot from "@mui/lab/TimelineDot";
import TimelineOppositeContent, {
  timelineOppositeContentClasses,
} from "@mui/lab/TimelineOppositeContent";
import { Card, IconButton, Typography } from "@mui/material";
import { Box } from "@mui/system";
import { SPACING } from "../data/spacing";
import { PropTypes } from "prop-types";
import React, { useEffect } from "react";
import { Grid } from "../components/grid/Grid";
import { useParams } from "react-router-dom";
import { formatTime } from "../utils/formatTime";
import { FileInformation } from "../features/file/components/file-information/FileInformation";
import { CityInformation } from "../features/file/components/city-information/CityInformation";
import CityFileOperations from "../features/file/components/city-file-operations/CityFileOperations";
import ProvinceCheckRequest from "../features/file/components/province-check-request/ProvinceCheckRequest";
import { ProvinceInformation } from "../features/file/components/province-information/ProvinceInformation";
import useRequestFile from "../features/file/hooks/useRequestFile";
import { ProvinceAllocation } from "../features/file/components/province-allocation/ProvinceAllocation";
import SlaughterCheckRequest from "../features/file/components/slaughter-check-request/SlaughterCheckRequest";
import SlaughterAssignCar from "../features/file/components/slaughter-assign-car/SlaughterAssignCar";
import useGetAllocationInformation from "../features/file/hooks/useGetAllocationInformation";
import { SlaughterEnterBarWeight } from "../features/file/components/slaughter-enter-bar-weight/SlaughterEnterBarWeight";
// import { useSlaughterAllocatedRequests } from "../features/file/hooks/useSlaughterAllocatedRequests";
import FinancialCheckRequestInformation from "../features/file/components/financial-check-request-information/FinancialCheckRequestInformation";
import useUserProfile from "../features/authentication/hooks/useUserProfile";
import { FinancialCheckRequestOperation } from "../features/file/components/financial-check-request-operation/FinancialCheckRequestOperation";
import { getRoleFromUrl } from "../utils/getRoleFromUrl";
import { SlaughterPayProvinceFactorForm } from "../features/file/components/slaughter-pay-province-factor-form/SlaughterPayProvinceFactorForm";
import SlaughterPaymentFactor from "../features/file/components/slaughter-payment-factor/SlaughterPaymentFactor";
import ProvinceFinancialSlaughterCheckRequest from "../features/file/components/province-financial-slaughter-check-request/ProvinceFinancialSlaughterCheckRequest";
import { Factor } from "../features/province-finacial/components/factor/Factor";
import FileAuctionStatus from "../features/file/components/file-auction-status/FileAuctionStatus";
import { FileAuctionWinner } from "../features/file/components/file-auction-winner/FileAuctionWinner";
import { ProvinceAllocationInformation } from "../features/file/components/province-allocation-information/ProvinceAllocationInformation";
import { InspectorRequestOperations } from "../features/file/components/inspector-request-operations/InspectorRequestOperations";
import { useAcceptedSlaughterRequest } from "../features/file/hooks/useAcceptedSlaughterRequest";
import SlaughterHouseVetCheckRequest from "../features/file/components/slaughter-house-vet-check-request/SlaughterHouseVetCheckRequest";
// import { useAcceptedSlaughterRequest } from "../features/file/hooks/useAcceptedSlaughterRequest";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { cleanFile } from "../lib/redux/slices/fileSlice";
// import { Timer } from "../components/timer/Timer";
// import moment from "moment";
import { getMonthlyPercent } from "../features/file/services/get-monthly-percent";
import { SlaughterPayPoultryFactorForm } from "../features/file/components/slaughter-pay-poultry-factor-form/SlaughterPayPoultryFactorForm";
import { SlaughterPaymentFactorPoultry } from "../features/file/components/slaughter-payment-factor-poultry/SlaughterPaymentFactorPoultry";

const File = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { id } = useParams();
  const myFile = useRequestFile(id);
  const [roles] = useUserProfile();
  // const slaughterAllocatedRequests = useSlaughterAllocatedRequests(id);
  const process = myFile?.file?.process;
  const { quantity, provinceAssignments } = useGetAllocationInformation(
    process?.poultry?.poultryRequestKey
  );

  useEffect(() => {
    dispatch(getMonthlyPercent());
  }, []);

  const provinceKillRequests = process?.provinceKillRequests;
  const acceptedSlaughterRequests = useAcceptedSlaughterRequest(id);

  const showEnterBarInfo = process?.auction
    ? !!process?.auction?.filter((item) => item.barInfo === null).length
    : provinceKillRequests?.some((killRequest, i) => {
        const { killHouseRequests } = killRequest;
        if (killHouseRequests) {
          return !!killHouseRequests?.filter(
            (item) =>
              item.barInfo === null ||
              item.barInfo?.killHouseAssignmentState === "rejected"
          ).length;
        }
        return false;
      });

  const showSlaughterHouseVetCheckRequest = process?.auction
    ? !!process?.auction?.filter((item) => item.barInfo === null).length
    : provinceKillRequests?.some((killRequest, i) => {
        const { killHouseRequests } = killRequest;
        if (killHouseRequests) {
          return !!killHouseRequests?.filter((item) => item.barInfo === null)
            .length;
        }
        return false;
      });

  useEffect(() => {
    return () => {
      dispatch(cleanFile());
    };
  }, []);

  const sellType = process?.filePaymentType;
  // const paymentPrice = "123000000";

  // const paymentDate = moment(new Date(2022, 11, 24, 10, 33, 30, 0));
  // const currentDate = moment();
  // const diff = paymentDate.diff(currentDate);
  // let paymentRemainedSeconds = moment.duration(diff).asSeconds();

  return (
    <>
      {process && (
        <Box mt={SPACING.MEDIUM} display={"flex"} justifyContent="center">
          <Grid
            container
            direction="column"
            justifyContent="center"
            xs={12}
            sm={12}
            md={10}
            lg={10}
          >
            <Grid container alignItems="center">
              <IconButton
                aria-label="delete"
                color="primary"
                onClick={() => navigate(-1)}
              >
                <NavigateNextIcon />
                <Typography>بازگشت</Typography>
              </IconButton>
            </Grid>
            <Card>
              <Grid
                container
                px={SPACING.SMALL}
                alignItems="center"
                gap={SPACING.TINY}
                justifyContent="space-between"
              >
                <Grid container direction="column">
                  <Grid container>
                    <Typography variant="h6">
                      مشخصات پرونده با کد سفارش{" "}
                      {process?.poultry?.poultryOrderCode}
                    </Typography>
                  </Grid>
                  <Grid container gap={SPACING.TINY}>
                    <Grid>
                      {!process?.poultry?.poultryAuction ? (
                        <Typography variant="body2" color="secondary">
                          (فروش از طریق اتحادیه)
                        </Typography>
                      ) : (
                        <Typography variant="body2" color="secondary">
                          (فروش از طریق مزایده)
                        </Typography>
                      )}
                    </Grid>
                    <Grid>
                      {sellType === "cash" && (
                        <Typography
                          variant="body2"
                          color={(prop) => prop.palette.warning.dark}
                        >
                          (فروش نقدی)
                        </Typography>
                      )}
                      {sellType === "credit" && (
                        <Typography
                          variant="body2"
                          color={(prop) => prop.palette.warning.dark}
                        >
                          (فروش زمان دار - تا یک ماه)
                        </Typography>
                      )}
                      {sellType === "cash_credit" && (
                        <Typography
                          variant="body2"
                          color={(prop) => prop.palette.warning.dark}
                        >
                          (فروش بصورت نقدی و زمان دار)
                        </Typography>
                      )}
                    </Grid>
                  </Grid>
                </Grid>

                <Grid container direction="column" alignItems="end">
                  {/* <Typography
                    variant="body1"
                    color={(prop) => prop.palette.action.dark}
                  >
                    مبلغ قابل پرداخت ={" "}
                    {paymentPrice.toLocaleString() + " ریال "}× 3% ماهانه
                  </Typography> */}
                  {/* <Grid container direction="column" gap={SPACING.TINY}>
                    <Typography>سررسید نزدیکترین قابل پرداخت</Typography>
                    <Timer
                      isFilePaymentTime={true}
                      seconds={paymentRemainedSeconds}
                    />
                  </Grid> */}
                  {/* <Grid>
                    <Typography
                      variant="body1"
                      color={(prop) => prop.palette.action.dark}
                    >
                      مبلغ قابل پرداخت ={" "}
                      {paymentPrice.toLocaleString() + " ریال "}× 3% ماهانه
                    </Typography>
                  </Grid> */}
                </Grid>
              </Grid>

              <Timeline
                sx={{
                  gap: SPACING.MEDIUM,
                  [`& .${timelineOppositeContentClasses.root}`]: {
                    // flex: 0.2,
                  },
                }}
              >
                <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 gap={SPACING.SMALL}>
                            <Typography
                              variant="body2"
                              display="flex"
                              gap={SPACING.SMALL}
                            >
                              درخواست در تاریخ
                            </Typography>
                            <Typography variant="body2" fontWeight="bold">
                              {formatTime(
                                process?.poultry?.poultryRegisterDate
                              )}
                            </Typography>
                            <Typography
                              variant="body2"
                              display="flex"
                              gap={SPACING.SMALL}
                            >
                              ثبت شده است.
                            </Typography>
                          </Grid>
                        </TimelineContent>
                      </Grid>
                    </Grid>
                    <Grid>
                      <Grid xs={12}>
                        <FileInformation file={process} />
                      </Grid>
                    </Grid>
                  </Grid>
                </TimelineItem>

                <CityInformation file={process} />
                {(getRoleFromUrl() === "CityOperator" ||
                  getRoleFromUrl() === "ProvinceOperator") &&
                  process.city === null && (
                    <CityFileOperations file={process} />
                  )}

                {process.auctionsList && process?.poultry?.poultryAuction && (
                  <FileAuctionStatus file={process} />
                )}

                {process.killHouseWinner && (
                  <FileAuctionWinner file={process} />
                )}

                {!process.auctionsList &&
                  !process.killHouseWinner &&
                  process?.city &&
                  process.city.cityState === "accept" && (
                    <ProvinceInformation quantity={quantity} file={process} />
                  )}

                {!process.killHouseWinner &&
                  getRoleFromUrl() === "ProvinceOperator" &&
                  roles.includes("ProvinceOperator") &&
                  process?.city &&
                  process?.province?.provinceState !== "reject" &&
                  process?.province?.provinceState !== "accept" && (
                    <ProvinceCheckRequest file={process} />
                  )}

                {!process.auctionsList &&
                  getRoleFromUrl() === "ProvinceOperator" &&
                  roles.includes("ProvinceOperator") &&
                  process?.city &&
                  process?.province?.provinceState === "accept" &&
                  quantity !== 0 && <ProvinceAllocation file={process} />}

                {!process.killHouseWinner &&
                  provinceAssignments &&
                  !!provinceKillRequests?.length &&
                  provinceAssignments?.map((item, i) => {
                    return (
                      <Grid key={"ProvinceAllocationInformation" + i}>
                        <Grid>
                          <ProvinceAllocationInformation item={item} i={i} />
                        </Grid>
                        <Grid>
                          {!process.killHouseWinner &&
                            getRoleFromUrl() === "KillHouse" &&
                            roles.includes("KillHouse") &&
                            Boolean(
                              provinceKillRequests?.filter(
                                (item) =>
                                  item.provinceKillReqState !== "accepted"
                              ).length
                            ) &&
                            item.provinceKillRequestState === "pending" && (
                              <SlaughterCheckRequest
                                key={"SlaughterCheckRequest" + i}
                                item={item}
                                i={i}
                                poultryRequestKey={
                                  process?.poultry?.poultryRequestKey
                                }
                              />
                            )}
                        </Grid>
                      </Grid>
                    );
                  })}

                {/* {!process.killHouseWinner &&
                  getRoleFromUrl() === "KillHouse" &&
                  roles.includes("KillHouse") &&
                  Boolean(
                    provinceKillRequests?.filter(
                      (item) => item.provinceKillReqState !== "accepted"
                    ).length
                  ) && <SlaughterCheckRequest file={process} />} */}

                {getRoleFromUrl() === "KillHouse" &&
                  roles.includes("KillHouse") &&
                  (acceptedSlaughterRequests.some(
                    (item) => item.quantity > 0
                  ) ||
                    (process.killHouseWinner &&
                      process.killHouseWinner.quantity > 0)) && (
                    <SlaughterAssignCar
                      file={process}
                      provinceAllocationLimit={
                        provinceAssignments
                          ? provinceAssignments[0]?.quantity
                          : 0
                      }
                    />
                  )}

                {showSlaughterHouseVetCheckRequest && (
                  <SlaughterHouseVetCheckRequest file={process} />
                )}

                {(getRoleFromUrl() === "KillHouse" ||
                  getRoleFromUrl() === "Poultry" ||
                  getRoleFromUrl() === "ProvinceFinancial") &&
                  (roles.includes("KillHouse") ||
                    roles.includes("Poultry") ||
                    roles.includes("ProvinceFinancial")) &&
                  !!showEnterBarInfo && (
                    <SlaughterEnterBarWeight file={process} />
                  )}

                {!process.killHouseWinner &&
                  provinceKillRequests?.map((killRequest, i) => {
                    const { killHouseRequests } = killRequest;
                    const d = killHouseRequests
                      ?.filter((item) => item.barInfo !== null)
                      .map((item, i) => {
                        const showSlaughterFactorForm =
                          (item.barInfo &&
                            item.provinceFactorToKillHouse &&
                            (!item.killHouseFactorToProvince ||
                              item.killHouseFactorToProvince.factorState ===
                                "rejected")) ||
                          (item.provinceFactorToKillHouseForPoultry &&
                            !item.killHouseFactorToPoultry) ||
                          item.killHouseFactorToPoultry?.factorState ===
                            "rejected";

                        const data = [
                          [
                            item.barcod,
                            `${item.killHouseName} (${item.killHouseUserProvince}/${item.killHouseUserCity})`,
                            item.quantity + " قطعه",
                            item.car?.driverName +
                              ` (${item.car?.driverMobile})`,
                            `${item.car?.typeCar} با پلاک ${item.car?.pelak}`,
                            item.barInfo.killHouseNetWeight + " کیلوگرم",
                            item.fee + " ریال",
                            <a
                              href={item.barInfo.killHouseImageWithoutLoad}
                              alt="دانلود سند خودرو بدون بار"
                              key="provinceKillRequests"
                            >
                              <img
                                src={item.barInfo.killHouseImageWithoutLoad}
                                width="100"
                                height="100"
                                alt="بدون بار"
                                className="images-file"
                              />
                            </a>,
                            <a
                              href={item.barInfo.killHouseImageWithLoad}
                              alt="دانلود سند خودرو با بار"
                              key="provinceKillRequests"
                            >
                              <img
                                src={item.barInfo.killHouseImageWithLoad}
                                width="100"
                                height="100"
                                alt="بدون بار"
                                className="images-file"
                                key="provinceKillRequests"
                              />
                            </a>,
                          ],
                        ];
                        return (
                          <Grid key={"killHouseRequests" + i}>
                            <FinancialCheckRequestInformation
                              item={data}
                              data={item}
                              auction={false}
                            />
                            {getRoleFromUrl() === "ProvinceFinancial" &&
                              roles.includes("ProvinceFinancial") &&
                              !item.provinceFactorToKillHouse &&
                              item.barInfo.killHouseAssignmentState ===
                                "pending" && (
                                <FinancialCheckRequestOperation
                                  item={item}
                                  file={process}
                                />
                              )}

                            {(getRoleFromUrl() === "KillHouse" ||
                              getRoleFromUrl() === "ProvinceFinancial") &&
                              (roles.includes("KillHouse") ||
                                roles.includes("ProvinceFinancial")) &&
                              showSlaughterFactorForm && (
                                <>
                                  {!item.killHouseFactorToProvince && (
                                    <SlaughterPayProvinceFactorForm
                                      key={`SlaughterPayProvinceFactorForm${i}`}
                                      factorKey={
                                        item.provinceFactorToKillHouse
                                          ?.provinceFactorKey
                                      }
                                      price={
                                        item.provinceFactorToKillHouse?.cost
                                      }
                                      provinceFactorToKillHouse={
                                        item.provinceFactorToKillHouse
                                      }
                                      isRejected={
                                        item?.killHouseFactorToProvince
                                          ?.factorState === "rejected"
                                      }
                                      killHouseFactorToProvince={
                                        item.killHouseFactorToProvince
                                      }
                                    />
                                  )}
                                  {item.provinceFactorToKillHouseForPoultry &&
                                    !item.killHouseFactorToPoultry && (
                                      <SlaughterPayPoultryFactorForm
                                        key={`SlaughterPayPoultryFactorForm${i}`}
                                        factorKey={
                                          item
                                            .provinceFactorToKillHouseForPoultry
                                            ?.provinceFactorKey
                                        }
                                        price={
                                          item
                                            .provinceFactorToKillHouseForPoultry
                                            ?.cost
                                        }
                                        provinceFactorToPoultry={
                                          item.provinceFactorToKillHouseForPoultry
                                        }
                                        isRejected={
                                          item?.killHouseFactorToPoultry
                                            ?.factorState === "rejected"
                                        }
                                        killHouseFactorToPoultry={
                                          item.killHouseFactorToPoultry
                                        }
                                      />
                                    )}
                                </>
                              )}
                          </Grid>
                        );
                      });
                    return d;
                  })}

                {process.killHouseWinner &&
                  process.auction
                    ?.filter((item) => item.barInfo !== null)
                    .map((item, i) => {
                      return (
                        <Grid key={"killHouseRequests" + i}>
                          <FinancialCheckRequestInformation
                            data={item}
                            auction={true}
                          />
                          {getRoleFromUrl() === "ProvinceFinancial" &&
                            roles.includes("ProvinceFinancial") &&
                            !item.provinceFactorToKillHouse && (
                              <FinancialCheckRequestOperation item={item} />
                            )}
                        </Grid>
                      );
                    })}

                {process.killHouseWinner &&
                  process.auction &&
                  process.auction
                    ?.filter(
                      (item) =>
                        item.barInfo &&
                        !item.killHouseFactorToProvince &&
                        item.provinceFactorToKillHouse
                    )
                    .map((item, i) => {
                      return (
                        <>
                          <FinancialCheckRequestInformation
                            data={item}
                            auction={true}
                          />
                          {getRoleFromUrl() === "KillHouse" &&
                            roles.includes("KillHouse") && (
                              <SlaughterPayProvinceFactorForm
                                key={`SlaughterPayProvinceFactorForm${i}`}
                                factorKey={
                                  item.provinceFactorToKillHouse
                                    ?.provinceFactorKey
                                }
                                price={item.provinceFactorToKillHouse?.cost}
                                provinceFactorToKillHouse={
                                  item.provinceFactorToKillHouse
                                }
                              />
                            )}
                        </>
                      );
                    })}

                {provinceKillRequests?.map((killRequest, i) => {
                  const { killHouseRequests } = killRequest;
                  return killHouseRequests
                    ?.filter(
                      (item) =>
                        item.barInfo &&
                        (item.killHouseFactorToProvince ||
                          item.killHouseFactorToPoultry)
                    )
                    .map((item, i) => {
                      return (
                        <>
                          {item?.killHouseFactorToProvince && (
                            <SlaughterPaymentFactor
                              key={`SlaughterPaymentFactor${i}`}
                              data={item.killHouseFactorToProvince}
                              barCode={item.barcod}
                            />
                          )}

                          {getRoleFromUrl() === "ProvinceFinancial" &&
                            roles.includes("ProvinceFinancial") &&
                            item?.killHouseFactorToProvince &&
                            item.killHouseFactorToProvince.factorState ===
                              "pending" && (
                              <>
                                <ProvinceFinancialSlaughterCheckRequest
                                  factorKey={
                                    item.killHouseFactorToProvince?.factorKey
                                  }
                                  factorType="province"
                                />
                              </>
                            )}

                          {item?.killHouseFactorToPoultry && (
                            <SlaughterPaymentFactorPoultry
                              key={`SlaughterPaymentFactor${i}`}
                              data={item.killHouseFactorToPoultry}
                              barCode={item.barcod}
                            />
                          )}

                          {item?.killHouseFactorToPoultry &&
                            getRoleFromUrl() === "ProvinceFinancial" &&
                            roles.includes("ProvinceFinancial") &&
                            item.killHouseFactorToPoultry.factorState ===
                              "pending" && (
                              <ProvinceFinancialSlaughterCheckRequest
                                factorKey={
                                  item.killHouseFactorToPoultry?.factorKey
                                }
                                factorType="poultry"
                              />
                            )}
                        </>
                      );
                    });
                })}

                {process.killHouseWinner &&
                  process.auction
                    ?.filter(
                      (item) => item.barInfo && item.killHouseFactorToProvince
                    )
                    .map((item, i) => {
                      return (
                        <>
                          <SlaughterPaymentFactor
                            key={`SlaughterPaymentFactor${i}`}
                            data={item.killHouseFactorToProvince}
                            barCode={item.barcod}
                          />
                          {getRoleFromUrl() === "ProvinceFinancial" &&
                            roles.includes("ProvinceFinancial") &&
                            item.killHouseFactorToProvince.factorState ===
                              "pending" && (
                              <ProvinceFinancialSlaughterCheckRequest
                                factorKey={
                                  item.killHouseFactorToProvince?.factorKey
                                }
                              />
                            )}
                        </>
                      );
                    })}

                {process.allocation && (
                  <Grid xs={12}>
                    <Factor process={process} />
                  </Grid>
                )}
                {getRoleFromUrl() === "ProvinceInspector" &&
                  roles.includes("ProvinceInspector") &&
                  process.allocation &&
                  process?.poultry?.poultryRequestFinalState === "archive" && (
                    <Grid>
                      <Grid xs={12}>
                        <InspectorRequestOperations process={process} />
                      </Grid>
                    </Grid>
                  )}
              </Timeline>
            </Card>
          </Grid>
        </Box>
      )}
    </>
  );
};

File.propTypes = {
  id: PropTypes.number,
};
export default File;
