import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import PaymentIcon from "@mui/icons-material/Payment";
import { IconButton, TextField, Typography } from "@mui/material";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { SlaughterPayFactor } from "../slaughter-pay-factor/SlaughterPayFactor";
import { slaughterFinalFactorsService } from "../../services/slaughter-final-factors";
import { Grid } from "../../../../components/grid/Grid";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import moment from "moment/moment";

export const SlaughterFinalFactorsComponent = () => {
  const dispatch = useDispatch();
  const { slaughterFinalFactors } = useSelector(
    (state) => state.slaughterSlice
  );
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

  useEffect(() => {
    const c = slaughterFinalFactors?.map((item) => {
      let state;
      switch (item.paidState) {
        case "pending":
          state = "در انتظار پرداخت";
          break;
        case "paid":
          state = "پرداخت شده";
          break;
        default:
          state = "در انتظار پرداخت";
      }
      return [
        item?.factorBarCode,
        state,
        item?.factorFee.toLocaleString() + " ﷼",
        item?.totalPrice.toLocaleString() + " ﷼",
        item?.totalWeight,
        <IconButton
          disabled={item.paidState === "paid"}
          key="ee"
          color="primary"
          onClick={() => {
            dispatch(
              DRAWER({
                title: "پرداخت فاکتور",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <SlaughterPayFactor
                    factorKey={item.key}
                    isFinalFactor={true}
                  />
                ),
              })
            );
          }}
        >
          <PaymentIcon />
        </IconButton>,
      ];
    });
    setDataFinalFactorsTable(c);
  }, [slaughterFinalFactors]);

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

  return (
    <Grid container flex={1}>
      <Grid width="100%">
        <AdvancedTable
          name={
            <Grid container alignItems="center" gap={SPACING.SMALL}>
              <Grid>
                <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={dataFinalFactorsTable}
        />
      </Grid>
    </Grid>
  );
};
