import { useState, useEffect, useCallback } from "react";
import { Grid } from "../../../../components/grid/Grid";
import axios from "axios";
import { useDispatch } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../../data/spacing";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ProvinceSmsSubmisionManagementOperation } from "../province-sms-submission-management-operation/ProvinceSmsSubmisionManagementOperation";

export const ProvinceSmsSubmissionManagement = () => {
  const dispatch = useDispatch();

  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);
  const [tableData, setTableData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);

  const fetchApiData = useCallback(async () => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(`management-send-sms/`);
      dispatch(LOADING_END());
      setData(response?.data || []);
      setTotalRows(response?.data?.count || 0);
    } catch (error) {
      dispatch(LOADING_END());
      console.error("Error fetching users:", error);
    }
  }, [dispatch]);

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

  const updateTable = useCallback(() => {
    fetchApiData(1);
  }, [fetchApiData]);

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

  const handlePerRowsChange = (newPerPage, page) => {
    setPerPage(newPerPage);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.name,
        item?.username,
        item?.password,
        <ProvinceSmsSubmisionManagementOperation
          updateTable_data={updateTable}
          key={`ops-${i}`}
          item={item}
          item_id={item?.id}
        />,
      ];
    });
    setTableData(d);
  }, [data]);

  return (
    <>
      <Grid
        container
        alignItems="center"
        mb={SPACING.SMALL}
        gap={SPACING.SMALL}
      ></Grid>

      <ResponsiveTable
        data={tableData}
        columns={["ردیف", "نام", "نام کابری", "رمز عبور", "ویرایش"]}
        handlePageChange={handlePageChange}
        handlePerRowsChange={handlePerRowsChange}
        totalRows={totalRows}
        title="مدیریت ارسال پیامک"
      />
    </>
  );
};
