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

export const SlaughterFactorsComponent = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);
  const { slaughterFactors } = useSelector((state) => state.slaughterSlice);
  const [dataTable, setDataTable] = useState([]);
  const [archiveDataTable, setArchiveDataTable] = useState([]);

  useEffect(() => {
    const d = slaughterFactors
      ?.filter((item) => item.state === "pending")
      .map((item) => {
        let state;
        switch (item.state) {
          case "pending":
            state = "در انتظار پرداخت";
            break;
          case "paid":
            state = "پرداخت شده";
            break;
          case "unpaid":
            state = "پرداخت نشده";
            break;
          default:
            state = "در انتظار پرداخت";
        }
        return [
          item?.killRequest?.slaughterHouse?.name
            ? item?.killRequest?.slaughterHouse?.name
            : item?.killRequest?.killHouse?.name,
          formatJustDate(item?.createDate),
          item?.killRequest?.IndexWeight,
          item.killRequest.oldChickenBreed
            ? item.killRequest.oldChickenBreed
            : item?.killRequest?.chickenBreed,
          item.killRequest.chickenBreed,
          item.killRequest.provinceQuantity
            ? item.killRequest.provinceQuantity.toLocaleString()
            : item.killRequest.killCapacity?.toLocaleString(),
          item.killRequest.provinceQuantity
            ? item.killRequest.killCapacity?.toLocaleString()
            : 0,
          item?.amount.toLocaleString() + " ﷼",
          item?.minimumAmount.toLocaleString() + " ﷼",
          state,
          <IconButton
            disabled={item.state === "paid"}
            key="ee"
            color="primary"
            onClick={() => {
              dispatch(
                DRAWER({
                  title: "پرداخت فاکتور",
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: <SlaughterPayFactor factorKey={item.key} />,
                })
              );
            }}
          >
            <PaymentIcon />
          </IconButton>,
          <IconButton
            disabled={item.paidState === "paid"}
            key="ee"
            color="error"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "لغو سفارش",
                  content: (
                    <Grid
                      container
                      direction="column"
                      alignItems="center"
                      justifyContent="center"
                      width="100%"
                      gap={SPACING.SMALL}
                    >
                      <Grid>
                        <Typography>
                          در صورت لغو فاکتور درخواست اولیه شما هم لغو می گردد.
                        </Typography>
                      </Grid>
                      <Grid>
                        <Button
                          variant="contained"
                          color="error"
                          onClick={() => {
                            dispatch(
                              slaughterDeleteFactorService({
                                state: "cancel",
                                factor_key: item.key,
                              })
                            ).then((r) => {
                              if (r.payload.error) {
                                dispatch(CLOSE_MODAL());
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: r.payload.error,
                                  severity: "error",
                                });
                              } else {
                                dispatch(
                                  slaughterFactorsService({
                                    selectedDate1,
                                    selectedDate2,
                                  })
                                );

                                dispatch(CLOSE_MODAL());
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "سفارش با موفقیت لغو شد.",
                                  severity: "success",
                                });
                              }
                            });
                          }}
                        >
                          لغو سفارش
                        </Button>
                      </Grid>
                    </Grid>
                  ),
                })
              );
            }}
          >
            <DeleteIcon />
          </IconButton>,
        ];
      });
    setDataTable(d);

    const c = slaughterFactors
      ?.filter((item) => item.state === "paid" || item.state === "unpaid")
      .map((item) => {
        let state;
        switch (item.state) {
          case "pending":
            state = "در انتظار پرداخت";
            break;
          case "paid":
            state = "پرداخت شده";
            break;
          case "unpaid":
            state = "پرداخت نشده";
            break;
          default:
            state = "در انتظار پرداخت";
        }
        return [
          item?.killRequest?.slaughterHouse?.name
            ? item?.killRequest?.slaughterHouse?.name
            : item?.killRequest?.killHouse?.name,
          formatJustDate(item?.createDate),
          item?.killRequest?.IndexWeight,
          item.killRequest.oldChickenBreed
            ? item.killRequest.oldChickenBreed
            : item?.killRequest?.chickenBreed,
          item.killRequest.chickenBreed,
          item.killRequest.provinceQuantity
            ? item.killRequest.provinceQuantity.toLocaleString()
            : item.killRequest.killCapacity?.toLocaleString(),
          item.killRequest.provinceQuantity
            ? item.killRequest.killCapacity?.toLocaleString()
            : 0,
          item?.amount.toLocaleString() + " ﷼",
          item?.minimumAmount.toLocaleString() + " ﷼",
          state,
        ];
      });
    setArchiveDataTable(c);
  }, [slaughterFactors]);

  useEffect(() => {
    dispatch(slaughterFactorsService({ 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={[
            "کاربر",
            "تاریخ درخواست",
            "وزن",
            "نژاد درخواستی",
            "نژاد تایید شده",
            "تعداد درخواستی",
            "تعداد تایید شده",
            "مبلغ پیش فاکتور",
            "حداقل پرداختی (70%)",
            "وضعیت",
            "پرداخت",
            "لغو سفارش",
          ]}
          data={dataTable}
        />
      </Grid>
      <Grid width="100%">
        <AdvancedTable
          name="بایگانی"
          columns={[
            "کاربر",
            "تاریخ درخواست",
            "وزن",
            "نژاد درخواستی",
            "نژاد تایید شده",
            "تعداد درخواستی",
            "تعداد تایید شده",
            "مبلغ پیش فاکتور",
            "حداقل پرداختی (70%)",
            "وضعیت",
          ]}
          data={archiveDataTable}
        />
      </Grid>
    </Grid>
  );
};
