import { IconButton, Tooltip, Typography } from "@mui/material";
import VisibilityIcon from "@mui/icons-material/Visibility";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { slaughterGetKillerKillhousesService } from "../../../slaughter-house/services/slaughter-get-killers-killhouses";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export function MonitoringBuyers() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const [dataTable, setDataTable] = useState();
  const { slaughterGetKillerKillhouses } = useSelector(
    (state) => state.slaughterSlice
  );

  // Get the first segment from pathname (adminx - could be superadmin or province)
  const getPathPrefix = () => {
    const segments = pathname.split("/").filter(Boolean);
    return segments[0] || "";
  };

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

  useEffect(() => {
    const d = slaughterGetKillerKillhouses?.map((item, i) => {
      const pathPrefix = getPathPrefix();

      return [
        i + 1,
        item?.killer ? "کشتارکن" : "کشتارگاه",
        <Grid key={item.key} alignItems="center" justifyContent="center">
          <Typography variant="caption">{item?.name}</Typography>
        </Grid>,
        <Grid
          container
          key={item.key}
          alignItems="center"
          justifyContent="center"
        >
          <Typography variant="caption">
            {item?.killHouseOperator?.user?.fullname} (
            {item?.killHouseOperator?.user?.mobile})
          </Typography>
        </Grid>,
        item?.uniqueIdentifier && (
          <Tooltip title="مشاهده جزییات" key={item.key}>
            <IconButton
              size="small"
              color="primary"
              onClick={() => {
                navigate(
                  `/${pathPrefix}/poultries/${item.uniqueIdentifier}?from=KillHouse`
                );
              }}
            >
              <VisibilityIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        ),
      ];
    });

    setDataTable(d);
  }, [slaughterGetKillerKillhouses, navigate, pathname]);

  return (
    <Grid mt={SPACING.SMALL}>
      <ResponsiveTable
        paginated
        title="خریداران"
        columns={[
          "ردیف",
          "ماهیت",
          "نام واحد",
          "نام و نام خانوادگی (تلفن)",
          "مشاهده جزییات",
        ]}
        data={dataTable}
      />
    </Grid>
  );
}
