import React, { useEffect, useState, useRef } from "react";
import { Box, Button, Grid, TextField, Chip } from "@mui/material";
import { useDispatch } from "react-redux";
import { slaughterGetDelegatesService } from "../../services/slaughter-get-delegates-service";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SPACING } from "../../../../data/spacing";
import { RiSearchLine } from "react-icons/ri";
import { DelegatesOperations } from "./DelegatesOperations";

export const StewardDelegatesTab = () => {
  const dispatch = useDispatch();
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const isFirstMount = useRef(true);

  const handleTextChange = (e) => setTextValue(e.target.value);

  const fetchApiData = async (pageNum) => {
    const response = await dispatch(
      slaughterGetDelegatesService({
        type: "Steward",
        search: "filter",
        value: textValue,
        page: pageNum,
        page_size: perPage,
      })
    );

    if (response.payload.error) {
      console.error("Error fetching data:", response.payload.error);
      setData([]);
      setTotalRows(0);
    } else {
      setData(response.payload.data?.results || []);
      const count = Number(response.payload.data?.count) || 0;
      setTotalRows(count);
    }
  };

  const handlePageChange = (pageNum) => {
    fetchApiData(pageNum);
    setPage(pageNum);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(Number(perRows));
    setPage(1);
  };

  const updateTableData = () => {
    fetchApiData(page);
  };

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }
    const d = data.map((item, i) => {
      const isActive = item?.active !== undefined ? item.active : !item?.trash;
      const hasLimitation = item?.limitation;
      const limitationBadge = (
        <Chip
          key={`limitation-${item?.key || i}`}
          label={hasLimitation ? "دارد" : "ندارد"}
          color={hasLimitation ? "warning" : "default"}
          size="small"
          sx={{ minWidth: 60 }}
        />
      );

      const stewardDisplay =
        item?.steward?.name && item?.steward?.user?.mobile
          ? `${item.steward.name} (${item.steward.user.mobile})`
          : item?.steward?.name
          ? item.steward.name
          : "-";

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.firstName || item?.first_name || "-",
        item?.lastName || item?.last_name || "-",
        item?.mobile || "-",
        item?.city || "-",
        stewardDisplay,
        limitationBadge,
        item?.governmentalLimitationWeight || 0,
        item?.freeLimitationWeight || 0,
        <Chip
          key={`status-${item?.key || i}`}
          label={isActive ? "فعال" : "غیرفعال"}
          color={isActive ? "success" : "error"}
          size="small"
          sx={{ minWidth: 80 }}
        />,
        <DelegatesOperations
          key={`operations-${item?.key || i}`}
          item={item}
          updateTable={updateTableData}
        />,
      ];
    });
    setTableData(d);
  }, [data, page, perPage]);

  useEffect(() => {
    fetchApiData(1);
  }, []);

  useEffect(() => {
    if (isFirstMount.current) {
      isFirstMount.current = false;
      return;
    }
    fetchApiData(1);
    setPage(1);
  }, [perPage]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setPage(1);
    const response = await dispatch(
      slaughterGetDelegatesService({
        type: "Steward",
        search: "filter",
        value: textValue,
        page: 1,
        page_size: perPage,
      })
    );

    if (response.payload.error) {
      console.error("Error fetching data:", response.payload.error);
      setData([]);
      setTotalRows(0);
    } else {
      setData(response.payload.data?.results || []);
      const count = Number(response.payload.data?.count) || 0;
      setTotalRows(count);
    }
  };

  return (
    <Box>
      <Grid container gap={SPACING.SMALL} mb={2}>
        <form onSubmit={handleSubmit} style={{ width: "100%" }}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 200 }}
              value={textValue}
              onChange={handleTextChange}
            />
            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </Grid>
        </form>
      </Grid>

      <Grid item xs={12}>
        <ResponsiveTable
          title="نمایندگان مباشرین"
          columns={[
            "ردیف",
            "نام",
            "نام خانوادگی",
            "شماره همراه",
            "شهر",
            "مباشر",
            "محدودیت فروش",
            "حداکثر فروش دولتی",
            "حداکثر فروش آزاد",
            "وضعیت",
            "عملیات",
          ]}
          customWidth={"100%"}
          data={tableData}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
        />
      </Grid>
    </Box>
  );
};
