import React, { useEffect, useState } from "react";
import { Box, Button, Grid, TextField, Chip } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { BackButton } from "../../../../components/back-button/BackButton";

import { OPEN_MODAL, CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { SlaughterManageDispensersForm } from "./SlaughterManageDispensersForm";
import { slaughterGetDispenserInfoService } from "../../services/slaughter-get-dispenser-info";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SPACING } from "../../../../data/spacing";
import { RiSearchLine } from "react-icons/ri";
import { formatJustDate } from "../../../../utils/formatTime";
import { SlaughterManageDispensersOperations } from "./SlaughterManageDispensersOperations";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

const SlaughterManageDispensers = () => {
  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 isSteward = getRoleFromUrl() === "Steward";
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const handleTextChange = (e) => setTextValue(e.target.value);

  const fetchApiData = async (pageNum) => {
    const response = await dispatch(
      slaughterGetDispenserInfoService({
        search: "filter",
        value: textValue,
        page: pageNum,
        page_size: perPage,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );

    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 !== 0 ? page : 1);
  };

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }
    const d = data.map((item, i) => {
      const isActive = item?.active !== undefined ? item.active : null;
      const statusBadge =
        isActive === null ? (
          "-"
        ) : (
          <Chip
            label={isActive ? "فعال" : "غیرفعال"}
            color={isActive ? "success" : "error"}
            size="small"
            sx={{ minWidth: 80 }}
          />
        );
      const hasLimitation = item?.limitation;
      const limitationBadge = (
        <Chip
          label={hasLimitation ? "دارد" : "ندارد"}
          color={hasLimitation ? "warning" : "default"}
          size="small"
          sx={{ minWidth: 60 }}
        />
      );
      const killhouseDisplay =
        item?.killHouse?.name && item?.killHouse?.mobile
          ? `${item.killHouse.name} (${item.killHouse.mobile})`
          : item?.killHouse?.name
          ? item.killHouse.name
          : "-";

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

      const displayValue = isSteward ? stewardDisplay : killhouseDisplay;

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.createDate ? formatJustDate(item.createDate) : "-",
        item?.nationalId || "-",
        item?.firstName || "-",
        item?.lastName || "-",
        item?.mobile || "-",
        item?.city || "-",
        item?.province || "-",
        displayValue,
        limitationBadge,
        item?.governmentalLimitationWeight || 0,
        item?.freeLimitationWeight || 0,
        statusBadge,
        <SlaughterManageDispensersOperations
          key={`operations-${item?.key || i}`}
          item={item}
          updateTable={updateTableData}
        />,
      ];
    });
    setTableData(d);
  }, [data, page, perPage]);

  useEffect(() => {
    fetchApiData(1);
    setPage(1);
  }, [perPage, selectedSubUser?.key]);

  useEffect(() => {
    fetchApiData(1);
  }, [selectedSubUser?.key]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setPage(1);
    const response = await dispatch(
      slaughterGetDispenserInfoService({
        search: "filter",
        value: textValue,
        page: 1,
        page_size: perPage,
        role_key:
          checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
            ? selectedSubUser?.key || ""
            : "",
      })
    );

    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 handleOpenModal = () => {
    dispatch(
      OPEN_MODAL({
        title: "ثبت توزیع کننده جدید",
        content: (
          <SlaughterManageDispensersForm
            onClose={() => dispatch(CLOSE_MODAL())}
            updateTable={updateTableData}
          />
        ),
        size: 300,
      })
    );
  };

  return (
    <Box display="flex" justifyContent="center">
      <Grid container xs={12} sm={12} md={10} lg={10}>
        <Grid item xs={12}>
          <BackButton />
        </Grid>
        <Grid container item gap={SPACING.SMALL}>
          <Button variant="contained" color="primary" onClick={handleOpenModal}>
            ثبت توزیع کننده جدید
          </Button>
          <form onSubmit={handleSubmit}>
            <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} mt={2}>
          <ResponsiveTable
            title="توزیع کنندگان"
            columns={[
              "ردیف",
              "تاریخ ایجاد",
              "کد ملی",
              "نام",
              "نام خانوادگی",
              "شماره همراه",
              "شهر",
              "استان",
              isSteward ? "مباشر" : "کشتارگاه",
              "محدودیت فروش",
              "حداکثر فروش دولتی",
              "حداکثر فروش آزاد",
              "وضعیت",
              "عملیات",
            ]}
            customWidth={"100%"}
            data={tableData}
            handlePageChange={handlePageChange}
            totalRows={totalRows}
            page={page}
            perPage={perPage}
            handlePerRowsChange={handlePerRowsChange}
          />
        </Grid>
      </Grid>
    </Box>
  );
};

export default SlaughterManageDispensers;
