import { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";

import { useDispatch } from "react-redux";

import EditIcon from "@mui/icons-material/Edit";

import { IconButton } from "@mui/material";

import { provincePolicyGetFinePermission } from "../../services/province-policy-get-fine-permission";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvincePolicyEditFine } from "../province-policy-edit-fine/ProvincePolicyEditFine";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const ProvincePolicyManagePenalty = () => {
  const dispatch = useDispatch();

  const [data, setData] = useState();
  const [tableData, setTableData] = useState();

  const fetchData = () => {
    dispatch(provincePolicyGetFinePermission()).then((r) => {
      setData(r.payload.data);
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        item?.name,
        item?.startTime &&
        item?.endTime &&
        item?.startTime !== "00:00:00" &&
        item?.endTime !== "00:00:00"
          ? `از ${item?.startTime.slice(0, 5)} تا ${item?.endTime.slice(0, 5)}`
          : "-",

        item?.fineCoefficient,
        item?.fine ? "فعال" : "غیر فعال",
        <Grid
          container
          alignItems="center"
          gap={12}
          justifyContent="center"
          key={i}
        >
          <IconButton
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش جریمه",
                  content: (
                    <ProvincePolicyEditFine fetchData={fetchData} item={item} />
                  ),
                })
              );
            }}
          >
            <EditIcon />
          </IconButton>
        </Grid>,
      ];
    });

    setTableData(d);
  }, [data]);

  return (
    <Grid container xs={12} justifyContent="start" alignItems="center">
      <ResponsiveTable
        name="جریمه"
        columns={["ردیف", "نام", "زمان", "ضریب جریمه", "وضعیت", "ویرایش"]}
        data={tableData}
        paginated
      />
    </Grid>
  );
};
