import { Button, IconButton, Tooltip, Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Grid } from "../../../../components/grid/Grid";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import { SPACING } from "../../../../data/spacing";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import BlockIcon from "@mui/icons-material/Block";
import InfoIcon from "@mui/icons-material/Info";
import List from "@mui/material/List";
import Card from "@mui/material/Card";
import CardHeader from "@mui/material/CardHeader";
import ListItemText from "@mui/material/ListItemText";
import ListItemIcon from "@mui/material/ListItemIcon";
import Checkbox from "@mui/material/Checkbox";
import CheckBoxOutlineBlankIcon from "@mui/icons-material/CheckBoxOutlineBlank";
import Divider from "@mui/material/Divider";
import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch, useSelector } from "react-redux";
import ProvinceFinancialSubmitDebtDocument from "../province-financial-submit-debt-document/ProvinceFinancialSubmitDebtDocument";
import { ProvinceFinancialSubmitFinancialDocument } from "../province-financial-submit-financial-document/ProvinceFinancialSubmitFinancialDocument";
import { Box } from "@mui/system";
import { ProvinceFinancialDebtorInfo } from "../province-financial-debtor-info/ProvinceFinancialDebtorInfo";
import { provinceFinancialGetUserFinancialInfo } from "../../services/province-financial-get-user-financial-info";
import { formatJustDate } from "../../../../utils/formatTime";
import Num2persian from "num2persian";
import ProvinceFinancialFinancialHistory from "../province-financial-financial-history/ProvinceFinancialFinancialHistory";
import { ROUTE_PROVINCE_FINANCIAL_FILE } from "../../../../routes/routes";
import { provinceFinancialChangeTransactionState } from "../../services/province-financial-change-transaction-state";

function not(a, b) {
  return a.filter((value) => b.indexOf(value) === -1);
}

function intersection(a, b) {
  return a.filter((value) => b.indexOf(value) !== -1);
}

function union(a, b) {
  return [...a, ...not(b, a)];
}

const ProvinceFinancialUserFinancial = () => {
  const { userFinancialInfo } = useSelector(
    (state) => state.provinceFinancialSlice
  );

  const [leftObject, setLeftObject] = useState({
    creditor: "",
    debtor: "",
    payable: "",
  });
  const [rightObject, setRighObject] = useState({
    creditor: "",
    debtor: "",
    payable: "",
  });

  const [selectedTransactions, setSelectedTransactions] = useState([]);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { userid } = useParams();
  const { profileid } = useParams();

  const [checked, setChecked] = React.useState([]);
  const [left, setLeft] = React.useState([]);
  const [right, setRight] = React.useState([]);

  const leftChecked = intersection(checked, left);
  const rightChecked = intersection(checked, right);

  const [dispatched, setDispatched] = useState(false);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(provinceFinancialGetUserFinancialInfo(userid)).then(() => {
      dispatch(LOADING_END());
      setDispatched(!dispatched);
    });
  }, []);

  useEffect(() => {
    setRight(userFinancialInfo);
  }, [dispatched]);

  const handleToggle = (value) => () => {
    const currentIndex = checked.indexOf(value);
    const newChecked = [...checked];

    if (currentIndex === -1) {
      newChecked.push(value);
    } else {
      newChecked.splice(currentIndex, 1);
    }

    setChecked(newChecked);
  };

  const isValidSelect = (rightChecked) => {
    if (rightChecked?.length === 0) {
      return true;
    } else {
      for (let index = 0; index < rightChecked?.length; index++) {
        if (rightChecked[index].transactionType === "creditor") {
          return true;
        } else {
          return false;
        }
      }
    }
  };

  const numberOfChecked = (items) => intersection(checked, items).length;

  const handleToggleAll = (items) => () => {
    const checkable = items.filter(
      (item) =>
        item.transactionType === "penalty" ||
        item.transactionType === "negative" ||
        item.transactionType === "positive" ||
        item.transactionType === "debtor" ||
        item.transactionType === "deposit"
    );
    if (numberOfChecked(checkable) === checkable?.length) {
      setChecked(not(checked, checkable));
    } else {
      setChecked(union(checked, checkable));
    }
  };

  const handleCheckedRight = () => {
    setRight(right.concat(leftChecked));
    setLeft(not(left, leftChecked));
    setChecked(not(checked, leftChecked));
  };

  const handleCheckedLeft = () => {
    setLeft(left.concat(rightChecked));
    setRight(not(right, rightChecked));
    setChecked(not(checked, rightChecked));
  };

  useEffect(() => {
    //hint: left is right!! because of rtl in persian :)
    let rightCreditorfilter = right?.filter(
      (item) => item?.transactionType === "creditor"
    );

    let rightCreditor = 0;
    for (let index = 0; index < rightCreditorfilter?.length; index++) {
      rightCreditor = rightCreditor + rightCreditorfilter[index].transferAmount;
    }

    let rightDebtorfilter = right?.filter(
      (item) => item.transactionType === "debtor"
    );

    let rightDebtor = 0;
    for (let index = 0; index < rightDebtorfilter?.length; index++) {
      rightDebtor = rightDebtor + rightDebtorfilter[index].transferAmount;
    }

    let rightPenaltyfilter = right?.filter(
      (item) => item.transactionType === "penalty"
    );

    let rightPenalty = 0;
    for (let index = 0; index < rightPenaltyfilter?.length; index++) {
      rightPenalty = rightPenalty + rightPenaltyfilter[index].transferAmount;
    }

    let rightDepositfilter = right?.filter(
      (item) => item.transactionType === "deposit"
    );

    let rightDeposit = 0;
    for (let index = 0; index < rightDepositfilter?.length; index++) {
      rightDeposit = rightDeposit + rightDepositfilter[index].transferAmount;
    }

    let rightPositivefilter = right?.filter(
      (item) => item.transactionType === "positive"
    );

    let rightPositive = 0;
    for (let index = 0; index < rightPositivefilter?.length; index++) {
      rightPositive = rightPositive + rightPositivefilter[index].transferAmount;
    }

    let rightNegativefilter = right?.filter(
      (item) => item.transactionType === "negative"
    );

    let rightNegative = 0;
    for (let index = 0; index < rightNegativefilter?.length; index++) {
      rightNegative = rightNegative + rightNegativefilter[index].transferAmount;
    }

    // end calculation right object

    let leftCreditorfilter = left?.filter(
      (item) => item.transactionType === "creditor"
    );

    let leftCreditor = 0;
    for (let index = 0; index < leftCreditorfilter?.length; index++) {
      leftCreditor = leftCreditor + leftCreditorfilter[index].transferAmount;
    }

    let leftDebtorfilter = left?.filter(
      (item) => item.transactionType === "debtor"
    );

    let leftDebtor = 0;
    for (let index = 0; index < leftDebtorfilter.length; index++) {
      leftDebtor = leftDebtor + leftDebtorfilter[index].transferAmount;
    }

    let leftPenaltyfilter = left?.filter(
      (item) => item.transactionType === "penalty"
    );

    let leftPenalty = 0;
    for (let index = 0; index < leftPenaltyfilter?.length; index++) {
      leftPenalty = leftPenalty + leftPenaltyfilter[index].transferAmount;
    }

    let leftDepositfilter = left?.filter(
      (item) => item.transactionType === "deposit"
    );

    let leftDeposit = 0;
    for (let index = 0; index < leftDepositfilter.length; index++) {
      leftDeposit = leftDeposit + leftDepositfilter[index].transferAmount;
    }

    let leftPositivefilter = left?.filter(
      (item) => item.transactionType === "positive"
    );

    let leftPositive = 0;
    for (let index = 0; index < leftPositivefilter?.length; index++) {
      leftPositive = leftPositive + leftPositivefilter[index].transferAmount;
    }

    let leftNegativefilter = left?.filter(
      (item) => item.transactionType === "negative"
    );

    let leftNegative = 0;
    for (let index = 0; index < leftNegativefilter?.length; index++) {
      leftNegative = leftNegative + leftNegativefilter[index].transferAmount;
    }

    //end calculation left object

    setLeftObject({
      creditor: leftCreditor + leftDeposit + leftPositive,
      debtor: leftDebtor + leftPenalty + leftNegative,
      payable:
        leftCreditor +
        leftDeposit +
        leftPositive -
        (leftDebtor + leftPenalty + leftNegative),
    });

    setRighObject({
      creditor: rightCreditor + rightDeposit + rightPositive,
      debtor: rightDebtor + rightPenalty + rightNegative,
      payable: Math.abs(
        rightCreditor +
          rightDeposit +
          rightPositive -
          (rightDebtor + rightPenalty + rightNegative)
      ),
    });

    const selects = left.map((item) => {
      return item.key;
    });
    setSelectedTransactions(selects);
  }, [left, right]);

  const customList = (title, items) => (
    <Card>
      <CardHeader
        avatar={
          <Checkbox
            onClick={handleToggleAll(items)}
            checked={
              numberOfChecked(items) === items?.length && items?.length !== 0
            }
            indeterminate={
              numberOfChecked(items) !== items?.length &&
              numberOfChecked(items) !== 0
            }
            disabled={items?.length === 0}
            inputProps={{
              "aria-label": "همه موارد انتخاب شده اند",
            }}
          />
        }
        title={title}
        subheader={`${numberOfChecked(items)}/${items?.length} انتخاب شده`}
      />
      <Divider />
      <List
        sx={{
          height: 250,
          bgcolor: "background.paper",
          overflow: "auto",
        }}
        dense
        component="div"
        role="list"
      >
        <Box sx={{ border: "1px dashed grey" }}>
          <Grid xs={12} display="flex" justifyContent="space-between">
            <Typography>انتخاب سند</Typography>
            <Typography>نوع سند</Typography>
            <Typography>کد پیگیری</Typography>
            <Typography>مبلغ</Typography>
            <Typography>زمان ثبت</Typography>
          </Grid>
        </Box>
        <Box>
          {items?.map((value, i) => {
            const labelId = `transfer-list-all-item-${value}-label`;
            return (
              <Grid key={i} display="flex" justifyContent="space-between">
                <Grid item>
                  <Tooltip
                    title={
                      value.transactionType === "creditor" &&
                      "امکان انجام عملیات روی تراکنش در انتظار پرداخت وجود ندارد"
                    }
                    placement="top-start"
                  >
                    <ListItemIcon>
                      <Checkbox
                        icon={
                          value.transactionType === "creditor" ? (
                            <BlockIcon />
                          ) : (
                            <CheckBoxOutlineBlankIcon />
                          )
                        }
                        color={"secondary"}
                        disabled={value.transactionType === "creditor"}
                        onClick={handleToggle(value)}
                        checked={checked.indexOf(value) !== -1}
                        tabIndex={-1}
                        disableRipple
                        inputProps={{
                          "aria-labelledby": labelId,
                        }}
                      />
                    </ListItemIcon>
                  </Tooltip>
                </Grid>
                <Grid item display="flex" alignItems="center">
                  <ListItemText
                    style={{
                      color:
                        value.transactionType === "creditor"
                          ? "blue"
                          : value.transactionType === "penalty"
                          ? "yellow"
                          : value.transactionType === "debtor"
                          ? "red"
                          : value.transactionType === "deposit"
                          ? "green"
                          : value.transactionType === "positive"
                          ? "purple"
                          : value.transactionType === "negative"
                          ? "brown"
                          : "pink",
                    }}
                    id={labelId}
                    primary={
                      value.transactionType === "creditor"
                        ? "پرداخت نشده"
                        : value.transactionType === "penalty"
                        ? "جریمه"
                        : value.transactionType === "debtor"
                        ? "بدهکار"
                        : value.transactionType === "deposit"
                        ? "واریزی"
                        : value.transactionType === "positive"
                        ? "بستانکار از سند"
                        : value.transactionType === "negative"
                        ? "بدهی از سند"
                        : "نامشخص"
                    }
                  />
                  <IconButton
                    disabled={
                      !(
                        value.transactionType === "deposit" &&
                        value.state === "waiting"
                      )
                    }
                    aria-label="delete"
                    color="primary"
                    onClick={() => {
                      dispatch(
                        DRAWER({ right: false, bottom: false, content: null })
                      );
                      dispatch(
                        OPEN_MODAL({
                          title: "تراکنش را تایید میکنید؟",
                          content: (
                            <Grid container gap={SPACING.SMALL}>
                              <Button
                                color="primary"
                                variant="contained"
                                onClick={() => {
                                  dispatch(LOADING_START());
                                  dispatch(
                                    provinceFinancialChangeTransactionState({
                                      transaction_key: value.key,
                                      state: "accepted",
                                    })
                                  ).then(() => {
                                    dispatch(LOADING_END());
                                    window.location.reload(false);
                                  });
                                }}
                              >
                                بله
                              </Button>
                              <Button
                                variant="outlined"
                                onClick={() => {
                                  dispatch(CLOSE_MODAL());
                                }}
                              >
                                خیر
                              </Button>
                            </Grid>
                          ),
                        })
                      );
                    }}
                  >
                    <InfoIcon />
                  </IconButton>
                </Grid>
                <Grid item>
                  {value.fileId > 0 ? (
                    <Button
                      size="small"
                      onClick={() => {
                        navigate(ROUTE_PROVINCE_FINANCIAL_FILE + value.fileId);
                      }}
                    >
                      {value.paymentCode}
                    </Button>
                  ) : (
                    <Button
                      size="small"
                      onClick={() => {
                        dispatch(
                          DRAWER({
                            right: !(window.innerWidth <= 600),
                            bottom: window.innerWidth <= 600,
                            content: (
                              <ProvinceFinancialDebtorInfo
                                paymentCode={value.paymentCode}
                              />
                            ),
                            title: "اطلاعات سند بدهکاری",
                          })
                        );
                      }}
                    >
                      {value.paymentCode}
                    </Button>
                  )}
                </Grid>
                {/* <ListItemButton
                      onClick={() => {
                        dispatch(
                          DRAWER({
                            right: !(window.innerWidth <= 600),
                            bottom: window.innerWidth <= 600,
                            content: <ProvinceFinancialDebtorInfo />,
                            title: "اطلاعات سند بدهکاری",
                          })
                        );
                      }}
                    >
                      {value.paymentCode}
                    </ListItemButton> */}
                <Grid item>
                  <ListItemText
                    id={labelId}
                    primary={value.transferAmount.toLocaleString() + " ریال"}
                  />
                </Grid>
                <Grid item>
                  <ListItemText
                    id={labelId}
                    primary={formatJustDate(value.createDate)}
                  />
                </Grid>
              </Grid>
            );
          })}
        </Box>
      </List>
    </Card>
  );

  return (
    <Grid>
      <Grid container alignItems="center">
        <IconButton
          aria-label="delete"
          color="primary"
          onClick={() => navigate(-1)}
        >
          <NavigateNextIcon />
          <Typography>بازگشت</Typography>
        </IconButton>
      </Grid>
      <Grid
        container
        direction="column"
        justifyContent="center"
        mt={SPACING.SMALL}
      >
        <Grid xs={12} container justifyContent="end" gap={SPACING.SMALL}>
          <Button
            className="new-request-form-button"
            variant={"contained"}
            onClick={() => {
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: (
                    <ProvinceFinancialSubmitDebtDocument
                      profileid={profileid}
                      walletkey={userid}
                    />
                  ),
                  title: "ایجاد سند جدید",
                })
              );
            }}
          >
            ایجاد سند جدید
          </Button>
          <Grid xs={12} display="flex" gap={SPACING.SMALL}>
            <SimpleTable
              columns={[
                "بستانکار",
                "بدهکار",
                "قابل واریز",
                "قابل واریز به حروف",
                "اقدام",
              ]}
              data={[
                [
                  leftObject.creditor.toLocaleString() + " ریال",
                  leftObject.debtor.toLocaleString() + " ریال",
                  Math.abs(leftObject.payable).toLocaleString() + " ریال",
                  Num2persian(Math.abs(leftObject.payable).toLocaleString()) +
                    " ریال",
                  <Button
                    disabled={left?.length === 0}
                    size="small"
                    key="test"
                    variant="outlined"
                    onClick={() => {
                      dispatch(
                        DRAWER({
                          right: !(window.innerWidth <= 600),
                          bottom: window.innerWidth <= 600,
                          content: (
                            <ProvinceFinancialSubmitFinancialDocument
                              paymentType={
                                leftObject.payable < 0
                                  ? "negative"
                                  : leftObject.payable > 1
                                  ? "positive"
                                  : "zero"
                              }
                              payable={leftObject.payable}
                              transactionsList={selectedTransactions}
                              userId={profileid}
                              userKey={userid}
                            />
                          ),
                          title: "ایجاد سند مالی",
                        })
                      );
                    }}
                  >
                    {leftObject.payable > 0 ? (
                      <>ایجاد سند مالی (طلبکار)</>
                    ) : leftObject.payable < 0 ? (
                      <>ایجاد سند مالی (بدهکار)</>
                    ) : (
                      <>ایجاد سند مالی </>
                    )}
                  </Button>,
                ],
              ]}
            />
            <SimpleTable
              columns={[
                "بستانکار",
                "بدهکار",
                "قابل واریز",
                "قابل واریز به حروف",
              ]}
              data={[
                [
                  rightObject.creditor.toLocaleString() + " ریال",
                  rightObject.debtor.toLocaleString() + " ریال",
                  rightObject.payable.toLocaleString() + " ریال",
                  Num2persian(rightObject.payable) + " ریال",
                ],
              ]}
            />
          </Grid>
        </Grid>

        <Grid
          xs={12}
          mt={SPACING.MEDIUM}
          container
          spacing={2}
          justifyContent="center"
          alignItems="center"
        >
          <Grid item xs={5.5}>
            {customList("انتخاب شده ها", left)}
          </Grid>
          <Grid item>
            <Grid container direction="column" alignItems="center">
              <Button
                sx={{ my: 0.5 }}
                variant="outlined"
                size="small"
                onClick={handleCheckedRight}
                disabled={leftChecked?.length === 0}
                aria-label="move selected right"
              >
                &gt;
              </Button>
              <Button
                sx={{ my: 0.5 }}
                variant="outlined"
                size="small"
                onClick={handleCheckedLeft}
                disabled={isValidSelect(rightChecked)}
                aria-label="move selected left"
              >
                &lt;
              </Button>
            </Grid>
          </Grid>
          <Grid item xs={5.5}>
            {customList("انتخاب شده", right)}
          </Grid>
        </Grid>

        <ProvinceFinancialFinancialHistory profileid={profileid} />
      </Grid>
    </Grid>
  );
};

export default ProvinceFinancialUserFinancial;
