import React, { useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { RiSearchLine } from "react-icons/ri";
import { fetchOutProvinceRealBuyers } from "../../services/province-out-province-buyers";
import { ProvinceTrueGuildsOutProvinceOperations } from "./ProvinceTrueGuildsOutProvinceOperations";

export const ProvinceTrueGuildsOutProvince = () => {
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  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 fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await fetchOutProvinceRealBuyers({
        role: getRoleFromUrl(),
        page: page,
        pageSize: perPage,
        searchValue: textValue,
      });
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };

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

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      const killHouseName = item?.KillHouse?.name || "-";
      const killHouseOperator =
        item?.KillHouse?.killHouseOperator?.user?.fullname || "";
      const killHouseInfo = killHouseOperator
        ? `${killHouseName} (${killHouseOperator})`
        : killHouseName;

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.fullname} (${item?.mobile})`,
        item?.unitName || "-",
        killHouseInfo,
        item?.province || "-",
        item?.city || "-",
        item?.requestsInfo?.numberOfRequests?.toLocaleString() || "0",
        item?.requestsInfo?.totalQuantity?.toLocaleString() || "0",
        item?.requestsInfo?.totalWeight?.toLocaleString() || "0",
        <ProvinceTrueGuildsOutProvinceOperations
          key={item?.unitName}
          item={item}
          updateTable={() => fetchApiData(1)}
        />,
      ];
    });

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

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    fetchApiData(1);
    setPage(1);
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              value={textValue}
              onChange={handleTextChange}
            />
            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "مشخصات خریدار",
          "نام واحد",
          "کشتارگاه",
          "استان",
          "شهر",
          "تعداد درخواست ها",
          "حجم تقریبی (قطعه)",
          "وزن (کیلوگرم)",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="اصناف حقیقی خارج استان"
      />
    </Grid>
  );
};
