import { useEffect, useState, useContext } from "react";
import {
  IonCard,
  IonCardContent,
  IonButton,
  IonText,
  IonSpinner,
} from "@ionic/react";

import { Context } from "../context/contex";
import { formatLocalTime } from "../utils";

const UserListPaginated: React.FC = () => {
  const context = useContext(Context);
   if (!context) {
  return <div>Loading...</div>;
 }
  const { apiURL, copy } = context;

  const [users, setUsers] = useState([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [busy, setBusy] = useState(false);

  const getUsers = async (page = 1, limit = 10) => {
    setBusy(true);

    try {
      const response = await fetch(apiURL, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({
          action: "get_paged_users",
          page: String(page),
          limit: String(limit),
        }),
      });

      const data = await response.json();

      if (data.success) {
        setUsers(data.users);
        setPage(page);
        setHasMore(page < data.total_pages);
      }
    } catch (err) {
      console.error("User fetch error:", err);
    }

    setBusy(false);
  };

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

  return (
    <IonCard>
      <IonCardContent>

        <h2 className="fw-bold ion-margin-bottom">All Users</h2>

        {busy ? (
          <IonSpinner />
        ) : users.length === 0 ? (
          <IonText>No users found.</IonText>
        ) : (
          <div style={{overflowX:"auto"}}>
          <table className="tx-table">
            <thead>
              <tr>
               <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Balance (NGN)</th>
                <th>Reg Date</th>
              </tr>
            </thead>

            <tbody>
              {users.map((u: any, i: number) => (
                <tr key={`u_${i}`}>
                  <td>{u.first_name}</td>
                  <td style={{cursor: 'pointer'}} onClick={() => copy(u.email)}>{u.email}</td>
                   <td>{u.phone}</td>
                  <td>₦{Number(u.ngn_balance).toLocaleString()}</td>
<td>{formatLocalTime(u.reg_date, 'date')}</td>
               
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        )}

        {/* Pagination */}
        <div className="pagination-row ion-margin-top">
          {page > 1 && (
            <IonButton
              size="small"
              fill="outline"
              onClick={() => getUsers(page - 1)}
            >
              Previous
            </IonButton>
          )}

          {hasMore && (
            <IonButton
              size="small"
              fill="solid"
              onClick={() => getUsers(page + 1)}
            >
              Next
            </IonButton>
          )}
        </div>
      </IonCardContent>
    </IonCard>
  );
};

export default UserListPaginated;
