import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import axios from "axios";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { IconButton } from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import { ProvinceRestrictionCarcassDistributionEdit } from "./ProvinceRestrictionCarcassDistributionEdit.js";

export const ProvinceRestrictionCarcassDistribution = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

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

  const fetchData = async () => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get("restriction_carcass_distribution/");
      dispatch(LOADING_END());
      setData(response?.data || []);
    } catch (error) {
      dispatch(LOADING_END());
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: error?.response?.data?.message || "خطا در دریافت اطلاعات",
        severity: "error",
      });
      console.error("Error fetching data:", error);
    }
  };

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

  const getDistributionTypeLabel = (type) => {
    const types = {
      KillHouse: "کشتارگاه",
      Steward: "مباشر",
    };
    return types[type] || type;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        getDistributionTypeLabel(item?.distributionType),
        item?.out ? "خارج استان" : "داخل استان",
        item?.time || "-",
        item?.allow ? "فعال" : "غیر فعال",
        <Grid
          container
          alignItems="center"
          gap={12}
          justifyContent="center"
          key={i}
        >
          <IconButton
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش محدودیت توزیع لاشه",
                  content: (
                    <ProvinceRestrictionCarcassDistributionEdit
                      fetchData={fetchData}
                      item={item}
                    />
                  ),
                })
              );
            }}
          >
            <EditIcon />
          </IconButton>
        </Grid>,
      ];
    });

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

  return (
    <>
      <ResponsiveTable
        title="محدودیت توزیع لاشه"
        columns={["ردیف", "نوع توزیع", "محل توزیع", "زمان", "وضعیت", "ویرایش"]}
        data={tableData}
        paginated={true}
      />
    </>
  );
};
