import { useEffect, useState, useContext } from "react";
import { Context } from "../../context/contex";

import {
  IonPage,
  IonSearchbar,
  IonText,
  IonButton,
  useIonRouter,
  IonRow,
  IonCol,
  IonLoading,
} from "@ionic/react";

import {
  renderTx
} from "../../utils";

import type { SearchbarChangeEventDetail } from "@ionic/react";
import AppShell from "../../components/Header";

/* ================= TYPES ================= */

interface Transaction {
  title: string;
  amount: number;
  status: string;
  date: number;
  currency: string;
  our_ref: string;
  flow: string;
  type: string;
  payload: any;
}

interface ApiResponse {
  success: boolean;
  transactions: Transaction[];
  total_pages: number;
}

/* ================= COMPONENT ================= */

const Transactions: React.FC = () => {
  const router = useIonRouter();
  const context = useContext(Context);

  if (!context) return null;

  const { apiURL, userInfo, busy, setBusy } = context;

  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [filtered, setFiltered] = useState<Transaction[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);

  /* 🔍 SEARCH */
  const handleInput = (ev: CustomEvent<SearchbarChangeEventDetail>) => {
    const query = (ev.detail.value || "").toLowerCase().trim();

    if (!query) {
      setFiltered([]);
      return;
    }

    setFiltered(
      transactions.filter(
        (t) =>
          t.title.toLowerCase().includes(query) ||
          t.our_ref.toLowerCase().includes(query)
      )
    );
  };

  /* 📡 FETCH TRANSACTIONS */
  const getTransactions = async (pageNum = 1, limit = 6) => {
    if (!userInfo) return;

    setBusy(true);
    try {
      const res = await fetch(apiURL, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({
          action: "get_paged_transactions",
          email: userInfo.email,
          page: String(pageNum),
          limit: String(limit),
        }),
      });

      const data: ApiResponse = await res.json();
      if (!data.success) return;

      setTransactions(data.transactions);
      setPage(pageNum);
      setHasMore(pageNum < data.total_pages);
    } catch (err) {
      console.error("Transaction fetch failed:", err);
    } finally {
      setBusy(false);
    }
  };

  /* INITIAL LOAD */
  useEffect(() => {
    if (userInfo) getTransactions(1);
  }, [userInfo]);

  const displayList = filtered.length > 0 ? filtered : transactions;
  const isSearching = filtered.length > 0;

  /* ================= RENDER ================= */

  return (
    <IonPage>
    <AppShell showBack={true} showLogo={false} title={"Transactions"}>
        <IonSearchbar
          debounce={400}
          placeholder="Search transactions"
         onIonInput={handleInput}
        />

     {renderTx(displayList, busy, false, router)}


        {/* 🔁 PAGINATION */}
        <IonRow className="ion-margin-top ion-justify-content-between">
          <IonCol size="6">
            <IonButton
              expand="block"
              fill="outline"
              disabled={page <= 1 || busy || isSearching}
              onClick={() => getTransactions(page - 1)}
            >
              Previous
            </IonButton>
          </IonCol>

          <IonCol size="6">
            <IonButton
              expand="block"
              disabled={!hasMore || busy || isSearching}
              onClick={() => getTransactions(page + 1)}
            >
              Next
            </IonButton>
          </IonCol>
        </IonRow>

        <IonLoading isOpen={busy} message="Loading transactions..." />
      </AppShell>
    </IonPage>
  );
};

export default Transactions;