import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import axios from "axios";
import { Button, IconButton, TextField } from "@mui/material";
import { RiSearchLine } from "react-icons/ri";
// import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { StewardSellOutOfProvinceAddBuyer } from "../steward-purchase-out-province-add-buyer/StewardSellOutOfProvinceAddBuyer";
import { StewardSellOutOfProvinceBuyersEditBuyer } from "../steward-sell-out-of-province-buyers-edit-buyer/StewardSellOutOfProvinceBuyersEditBuyer";

export const StewardSellOutOfProvinceBuyers = () => {
  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) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `out-province-carcasses-buyer/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&state=buyer-list`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

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

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

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.fullname} (${item?.mobile})`,
        item?.unitName,
        item?.province,
        item?.city,
        item?.requestsInfo?.numberOfRequests?.toLocaleString(),
        item?.requestsInfo?.totalQuantity?.toLocaleString(),
        item?.requestsInfo?.totalWeight?.toLocaleString(),
        <IconButton
          color="primary"
          key={i}
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <StewardSellOutOfProvinceBuyersEditBuyer
                    updateTable={updateTable}
                    isEdit
                    data={item}
                  />
                ),
                title: "ویرایش خریدار",
              })
            );
          }}
        >
          <EditIcon />
        </IconButton>,
      ];
    });

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

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `out-province-carcasses-buyer/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}&state=buyer-list`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <StewardSellOutOfProvinceAddBuyer updateTable={updateTable} />
                ),
                title: "افزودن خریدار",
              })
            );
          }}
        >
          افزودن خریدار
        </Button>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              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>
  );
};
