import { Button, Card, IconButton } from "@mui/material";
import { useEffect, useState } from "react";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { useDispatch, useSelector } from "react-redux";
import { slaughterGetCars } from "../../services/slaughter-get-cars";
import DeleteIcon from "@mui/icons-material/Delete";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { slaughterDeleteCar } from "../../services/slaughter-delete-car";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { SlaughterNewCar } from "../slaughter-new-car/SlaughterNewCar";
import { AppContext } from "../../../../contexts/AppContext";
import { useContext } from "react";
import { slaughterGetProfile } from "../../services/slaughter-get-profile";

export const SlaughterManageCars = () => {
  const [dataTable, setDataTable] = useState([]);
  const { slaughterHouseCars, profile } = useSelector(
    (state) => state.slaughterSlice
  );
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

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

  useEffect(() => {
    const filteredData = slaughterHouseCars;
    const d = filteredData?.map((item, i) => {
      return [
        i + 1,
        item.typeCar,
        item.pelak,
        item.capocity,
        parseInt(item.healthCode),
        // Number(item.healthCode),
        item.driverName,
        item.driverMobile,
        // @todo make onclick delete the car
        <IconButton
          key={i}
          aria-label="delete"
          color="error"
          onClick={() => {
            dispatch(LOADING_START());
            dispatch(
              slaughterDeleteCar({
                id: item.id,
              })
            ).then((r) => {
              if (r.error) {
                if (r.error.message.includes("403")) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "امکان حذف بدلیل تخصیص بار فعال به خودرو وجود ندارد!",
                    severity: "error",
                  });
                } else {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "مشکلی پیش آمده است!",
                    severity: "error",
                  });
                }
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
              dispatch(slaughterGetCars());
              dispatch(LOADING_END());
            });
          }}
        >
          <DeleteIcon />
        </IconButton>,
      ];
    });

    setDataTable(d);
  }, [slaughterHouseCars]);

  const [tableDataCol] = useState([
    "ردیف",
    "مدل خودرو",
    "پلاک",
    "ظرفیت",
    "کد بهداشتی",
    "نام راننده",
    "موبایل راننده",
    "حذف",
  ]);
  return (
    <>
      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        gap={SPACING.SMALL}
        xs={12}
      >
        <Grid>
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: (
                    <SlaughterNewCar
                      cars={slaughterHouseCars}
                      killHouseKey={profile?.killHouse[0]?.key}
                    />
                  ),
                  title: "ثبت خودرو جدید",
                })
              );
            }}
          >
            ثبت خودرو جدید
          </Button>
        </Grid>
        <Card sx={{ width: "100%" }}>
          <AdvancedTable columns={tableDataCol} data={dataTable} />
        </Card>
      </Grid>
    </>
  );
};
