import {
 IonPage,
 IonHeader,
 IonToolbar,
 IonButtons,
 IonBackButton,
 IonTitle,
 IonContent,
 IonSearchbar,
 IonSegment,
 IonSegmentButton,
 IonLabel,
 IonRow,
 IonCol,
 IonText,
 IonSpinner,
} from "@ionic/react";
import { arrowBackOutline } from "ionicons/icons";
import { useEffect, useState, useContext } from "react";
import { Context } from "../../context/contex";
import {
 formatNumber,
 txColor,
 getCurrencySymbol,
 formatLocalTime,
 renderTx
} from "../../utils/index";
import axios from "axios";
import { useIonRouter } from "@ionic/react";

const AdminTransactions: React.FC = () => {
 const context = useContext(Context);
 if (!context) return <div>Loading...</div>;
   const router = useIonRouter();

 const { apiURL, presentToast, userInfo } = context;
 const [segment, setSegment] = useState<"all" | "search">("all");
 const [loading, setLoading] = useState(false);
 const [transactions, setTransactions] = useState<any[]>([]);
 const [query, setQuery] = useState("");
 const [results, setResults] = useState<any[]>([]);

 // 🔹 Fetch last 100 transactions (admin-wide)
 const fetchAll = async () => {
  try {
   setLoading(true);
   const res = await axios.post(
    apiURL,
    new URLSearchParams({
     action: "get_all_transactions",
     limit: "100",
    }),
    { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
   );
   if (res.data.success) setTransactions(res.data.transactions);
   else
    presentToast(
     "top",
     res.data.message || "No transactions found",
     () => null,
     "warning"
    );
  } catch (err: any) {
   console.error(err);
   presentToast("top", "Error fetching transactions", () => null, "danger");
  } finally {
   setLoading(false);
  }
 };

 // 🔍 Search by email or reference
 const handleSearch = async (e: CustomEvent) => {
  const val = (e.target as HTMLInputElement).value.trim();
  setQuery(val);
  if (!val) {
   setResults([]);
   return;
  }

  try {
   setLoading(true);
   const res = await axios.post(
    apiURL,
    new URLSearchParams({
     action: "search_transactions",
     query: val,
    }),
    { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
   );

   if (res.data.success) setResults(res.data.transactions);
   else setResults([]);
  } catch (error) {
   console.error(error);
   presentToast("top", "Error searching transactions", () => null, "danger");
  } finally {
   setLoading(false);
  }
 };

 useEffect(() => {
  fetchAll();
 }, []);

 const renderList = (list: any[]) => {
  if (loading) {
   return (
    <div className="ion-text-center ion-margin-top">
     <IonSpinner name="crescent" />
    </div>
   );
  }

  if (list.length === 0) {
   return (
    <IonText color="medium" className="ion-text-center ion-margin-top">
     <p>No transactions found.</p>
    </IonText>
   );
  }

  return list.map((tx, index) => (
   <IonRow key={`tx_${index}`} className="ion-margin-vertical">
    <IonCol size="9">
     <IonText
      style={{ cursor: "pointer" }}
      onClick={() => (window.location.href = `/tx?tx=${tx.our_ref}`)}
     >
      <b>{tx.title || "Transaction"}</b>
     </IonText>
     <br />
     <small>
      {tx.email ? `${tx.email}` : ""} • {formatLocalTime(tx.date)}
     </small>
    </IonCol>
    <IonCol size="3" className="ion-text-right">
     <IonText>
      <b>
       {getCurrencySymbol(tx.currency)}
       {formatNumber(tx.amount)}
      </b>
     </IonText>
     <br />
     <small className={txColor(tx.status, tx.flow)}>{tx.status}</small>
    </IonCol>
   </IonRow>
  ));
 };

 return (
  <IonPage>
   <IonHeader>
    <IonToolbar className="ion-padding-horizontal">
     <IonButtons slot="start">
      <IonBackButton text="" icon={arrowBackOutline} defaultHref="/" />
     </IonButtons>
     <IonTitle>All Transactions</IonTitle>
    </IonToolbar>
   </IonHeader>
   {userInfo && userInfo?.is_admin && (
    <IonContent fullscreen className="ion-padding ion-content-bg">
     <IonSegment
      value={segment}
      onIonChange={(e) => setSegment(e.detail.value as "all" | "search")}
     >
      <IonSegmentButton value="all">
       <IonLabel>Recent (100)</IonLabel>
      </IonSegmentButton>
      <IonSegmentButton value="search">
       <IonLabel>Search</IonLabel>
      </IonSegmentButton>
     </IonSegment>

     {segment === "search" && (
      <IonSearchbar
       debounce={800}
       placeholder="Search by email or reference"
       onIonInput={handleSearch}
      />
     )}

     <div className="ion-padding-top">
     {segment === "all" ? renderTx(transactions, loading, true, router) : renderTx(results, loading, true, router)}
     </div>
    </IonContent>
   )}
  </IonPage>
 );
};

export default AdminTransactions;
