import {
 IonPage,
 IonHeader,
 IonToolbar,
 IonTitle,
 IonContent,
 IonCard,
 IonCardContent,
 IonList,
 IonItem,
 IonLabel,
 IonButton,
 IonIcon,
 IonText,
 IonSpinner,
 IonButtons,
 IonBackButton,
 IonLoading,
 IonRow,
 IonCol,
 IonGrid,
} from "@ionic/react";
import {
 checkmarkCircleOutline,
 shareSocialOutline,
 copyOutline,
 arrowBackOutline,
 closeCircleOutline,
 timeOutline,
 checkmarkDoneCircle,
} from "ionicons/icons";
import React, { useEffect, useState, useContext } from "react";
import axios from "axios";
import { Context } from "../../context/contex";
import Ads from "../../components/Ads";
import TransactionDetails from "../../components/transaction";
import {
 formatNumber,
 shortenAddress,
 getQueryParam,
 formatLocalTime,
 getCurrencySymbol,
} from "../../utils";
import { Share } from "@capacitor/share";
import { Filesystem, Directory, Encoding } from "@capacitor/filesystem";
import { Capacitor } from "@capacitor/core";


interface TxPayload {
 [key: string]: any;
}

interface userInfoProps {
 first_name: string;
 last_name: string;
}

const Tx: React.FC = () => {
 const [tx, setTx] = useState<TxPayload>({});
 const [type, setType] = useState<string>("");
 const [data, setData] = useState<any>(null);
 const [sInfo, setSInfo] = useState<userInfoProps | null>(null);
 const [rInfo, setRInfo] = useState<userInfoProps | null>(null);

 const context = useContext(Context);

 if (!context) {
  return <div>Loading...</div>;
 }

 const { apiURL, settings, busy, setBusy, copy, storage } = context;
 const id = getQueryParam("tx");

 const getTx = async (id: string) => {
  if (!id) return;
  setBusy(true);
  //console.log("TXID", id);

  try {
   const response = await axios.post(
    apiURL,
    new URLSearchParams({
     action: "get_tx_details",
     id,
    }),
    {
     headers: { "Content-Type": "application/x-www-form-urlencoded" },
    }
   );

   const res = response.data;
   // console.log("DAA", res);
   if (!res.error) {
    setData(res);
    setType(res.type);
    if (res.payload) {
     try {
      const fixed = res.payload.replace(/\\"/g, '"').replace(/^"|"$/g, "");
      const parsed = JSON.parse(fixed);
      setTx(parsed);
     } catch (err: any) {
      console.error("Failed to parse payload:", err.message);
     }
    }
   } else {
    console.error("Error:", res);
   }
  } catch (err: any) {
   console.error("Error fetching tx:", err);
  } finally {
   setBusy(false);
  }
 };

 useEffect(() => {
  getTx(id as string);
 }, [id]);

 const getToken = (str: string) => {
  const arr = str.split(" ");
 // return arr[arr.length - 1];
 return str;
 };

 const doSplit = (str: string) => {
  const arr = str?.split(" ")[0];
  return arr;
 };

 const handleShare = async () => {
  const pdfUrl = `${settings?.domain}uploads/receipts/receipt-${id}.pdf`;

  try {
   // Try to download the PDF file and share the actual file
   const response = await fetch(pdfUrl);
   const blob = await response.blob();
   const arrayBuffer = await blob.arrayBuffer();
   const base64 = btoa(
    new Uint8Array(arrayBuffer).reduce(
     (data, byte) => data + String.fromCharCode(byte),
     ""
    )
   );

   // Save file locally
   const fileName = "receipt.pdf";
   const savedFile = await Filesystem.writeFile({
    path: fileName,
    data: base64,
    directory: Directory.Cache,
   });

   // Get the file URI to share
   const fileUri = Capacitor.convertFileSrc(savedFile.uri);

   // Share the file
   await Share.share({
    title: "Vinpace Transaction Receipt",
    text: "Here’s your Vinpace transaction receipt.",
    url: fileUri,
    dialogTitle: "Share receipt via",
   });

   console.log("Receipt shared successfully!");
  } catch (error) {
   console.warn("Could not share actual file, falling back to link:", error);

   // Fallback: just share the link
   await Share.share({
    title: "Vinpace Transaction Receipt",
    text: "Here’s your Vinpace transaction receipt.",
    url: pdfUrl,
   });
  }
 };

 const getUsers = async () => {
  if (!id || (!id.startsWith("send_") && !id.startsWith("sl_"))) return;
  if (
   !data ||
   Object.keys(data).length === 0 ||
   !data.sender ||
   !data.recipient
  )
   return;
  const token = await storage?.get("vin_auth_token");

  try {
   const headers = { "Content-Type": "application/x-www-form-urlencoded",  Authorization: `Bearer ${token}`, };

   const [response1, response2] = await Promise.all([
    fetch(apiURL, {
     method: "POST",
     headers,
     body: new URLSearchParams({ action: "get_tx_user_info", email: data.sender }),
    }),
    fetch(apiURL, {
     method: "POST",
     headers,
     body: new URLSearchParams({
      action: "get_tx_user_info",
      email: data.recipient,
     }),
    }),
   ]);

   if (!response1.ok || !response2.ok) {
    throw new Error(`HTTP error! ${response1.status} / ${response2.status}`);
   }

   const [data1, data2] = await Promise.all([
    response1.json(),
    response2.json(),
   ]);

   if (data1.error || data2.error) {
    console.error("Error:", data1.error || data2.error);
    return;
   }
console.log("DATA", data1);
   setSInfo(data1[0]);
   setRInfo(data2[0]);
  } catch (error: any) {
   console.error("❌ Error fetching users:", error?.message || error);
  }
 };

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

 const status =
  tx?.content?.transactions?.status?.toLowerCase() ||
  tx?.status?.toLowerCase() ||
  data?.status?.toLowerCase() ||
  tx?.data?.status?.toLowerCase() ||
  "pending";

 const isSuccess = [
  "successful",
  "completed",
  "complete",
  "delivered",
  "done",
  "success",
 ].includes(status);
 const isFailed = ["failed", "error", "fail"].includes(status);
 const isPending = ["pending", "processing"].includes(status);

 const statusColor = isSuccess ? "success" : isFailed ? "danger" : "warning";
 const statusIcon = isSuccess
  ? checkmarkDoneCircle
  : isFailed
  ? closeCircleOutline
  : timeOutline;
 const statusText = isSuccess
  ? "Transaction Completed"
  : isFailed
  ? "Transaction Failed"
  : "Transaction Pending";

 return (
  <>
   <IonPage>
    <IonHeader className="transaction-header">
     <IonToolbar color="darkblue" className="header-toolbar">
      <IonButtons slot="start">
       <IonBackButton defaultHref="/" text="" style={{ color: "white" }} />
      </IonButtons>
     </IonToolbar>
     <div className="ion-text-center ion-margin-bottom">
      <IonIcon
       icon={statusIcon}
       color={statusColor}
       style={{ fontSize: "60px" }}
      />
      <IonText color="success">
       <h2 className="header-title">{statusText}</h2>
      </IonText>
     </div>
    </IonHeader>

    <IonLoading
     isOpen={busy}
     message="Please wait..."
     spinner="circles"
     className="custom-loading"
    />

    <IonContent fullscreen>
     <>
      {tx && Object.keys(tx).length > 0 && (
       <>
        {type === "education" && (
         <IonCard>
          <IonCardContent>
           <IonList>
            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Product</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              {tx.content?.transactions?.product_name}
             </IonLabel>
            </IonItem>

            {tx.content?.transactions?.quantity && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Quantity</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.quantity}
              </IonLabel>
             </IonItem>
            )}

            {tx.content?.transactions?.unit_price && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Unit Price</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               ₦{formatNumber(tx.content.transactions.unit_price)}
              </IonLabel>
             </IonItem>
            )}

            {tx.content?.transactions?.convinience_fee && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Convenience Fee</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               ₦{formatNumber(tx.content.transactions.convinience_fee)}
              </IonLabel>
             </IonItem>
            )}

            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Total Amount</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              ₦{formatNumber(tx.amount)}
             </IonLabel>
            </IonItem>
 {data.date && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Date</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {formatLocalTime(
                data.date)}
              </IonLabel>
             </IonItem>
            )}
            {tx.content?.transactions?.status && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Status</IonLabel>
              <IonLabel
               className={`tx-value ion-text-right ${
                tx.content.transactions.status === "Completed"
                 ? "status-success"
                 : "status-failed"
               }`}
              >
               {tx.content.transactions.status}
              </IonLabel>
             </IonItem>
            )}

            {/* Display Tokens */}
            {tx.tokens &&
             tx.tokens.length > 0 &&
             tx.tokens.map((pin: string, i: number) => (
              <IonItem key={i} lines="none" className="tx-row">
               <IonLabel className="tx-label">PIN {i + 1}</IonLabel>
               <IonLabel className="tx-value ion-text-right">{pin}</IonLabel>
               <IonButton fill="clear" slot="end" onClick={() => copy(pin)}>
                <IonIcon icon={copyOutline} />
               </IonButton>
              </IonItem>
             ))}

            {/* Display Cards */}
            {tx.cards &&
             tx.cards.length > 0 &&
             tx.cards.map((pin: any, i: number) => (
              <IonItem key={i} lines="none" className="tx-row ion-text-wrap">
               <IonLabel className="tx-label">Card {i + 1}</IonLabel>
               <IonLabel className="tx-value ion-text-right">
                <p>
                 Pin: {pin.Pin}{" "}
                 <IonIcon
                  icon={copyOutline}
                  color="primary"
                  onClick={() => copy(pin.Pin)}
                  style={{ cursor: "pointer", marginLeft: 5 }}
                 />
                </p>
                <p>
                 SN: {pin.Serial}{" "}
                 <IonIcon
                  icon={copyOutline}
                  color="primary"
                  onClick={() => copy(pin.Serial)}
                  style={{ cursor: "pointer", marginLeft: 5 }}
                 />
                </p>
               </IonLabel>
              </IonItem>
             ))}

            {/* Purchased Code */}
            {tx.purchased_code && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">PIN</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {getToken(tx.purchased_code)}
              </IonLabel>
              <IonButton
               fill="clear"
               slot="end"
               onClick={() => copy(getToken(tx.purchased_code))}
              >
               <IonIcon icon={copyOutline} />
              </IonButton>
             </IonItem>
            )}
           </IonList>
          </IonCardContent>
         </IonCard>
        )}

        {type === "electricity" && (
         <IonCard>
          <IonCardContent>
           <IonList>
            {(tx.customerName || tx.Name) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Name</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.customerName || tx.Name}
              </IonLabel>
             </IonItem>
            )}

            {(tx.customerAddress || tx.Address) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Address</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.customerAddress || tx.Address}
              </IonLabel>
             </IonItem>
            )}

            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Amount</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              ₦{formatNumber(tx.amount)}
             </IonLabel>
            </IonItem>

            {tx.balance && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Balance</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.balance}
              </IonLabel>
             </IonItem>
            )}

            {tx.purchased_code && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Token</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {getToken(tx.purchased_code)}
              </IonLabel>
              <IonButton
               fill="clear"
               slot="end"
               onClick={() => copy(getToken(tx.purchased_code))}
              >
               <IonIcon icon={copyOutline} />
              </IonButton>
             </IonItem>
            )}

            {(tx.units || tx.PurchasedUnits) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Units</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.units || tx.PurchasedUnits}
              </IonLabel>
             </IonItem>
            )}

            {(tx.tariff || tx.TariffRate) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Tariff</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.tariff || tx.TariffRate}
              </IonLabel>
             </IonItem>
            )}

            {tx.MeterCategory && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Meter Category</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.MeterCategory}
              </IonLabel>
             </IonItem>
            )}

            {tx.MeterNumber && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Meter Number</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.MeterNumber}
              </IonLabel>
             </IonItem>
            )}

            {tx.content?.transactions?.type && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Type</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.type}
              </IonLabel>
             </IonItem>
            )}

            {tx.content?.transactions?.product_name && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Product</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.product_name}
              </IonLabel>
             </IonItem>
            )}

 {data.date && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Date</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {formatLocalTime(
                data.date)}
              </IonLabel>
             </IonItem>
            )}

            {tx.content?.transactions?.status && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Status</IonLabel>
              <IonLabel
               className={`tx-value ion-text-right ${
                tx.content.transactions.status === "Completed"
                 ? "status-success"
                 : "status-failed"
               }`}
              >
               {tx.content.transactions.status}
              </IonLabel>
             </IonItem>
            )}
           </IonList>
          </IonCardContent>
         </IonCard>
        )}

        {type === "crypto" && (
         <IonCard>
          <IonCardContent>
           <IonList>
            {tx.from_currency && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">From Currency</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.from_currency?.toUpperCase()}
              </IonLabel>
             </IonItem>
            )}

            {tx.to_currency && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">To Currency</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.to_currency?.toUpperCase()}
              </IonLabel>
             </IonItem>
            )}

            {tx.from_amount && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Amount Paid</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx?.from_amount} {tx.from_currency?.toUpperCase()}
              </IonLabel>
             </IonItem>
            )}
{data.amount &&
            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Amount Received</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              {formatNumber(data?.amount, 6)} {tx.to_currency?.toUpperCase()}
             </IonLabel>
            </IonItem>
        }
            {tx.txid && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Transaction Hash</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {shortenAddress(tx.txid)}
              </IonLabel>
              <IonButton fill="clear" slot="end" onClick={() => copy(tx.txid)}>
               <IonIcon icon={copyOutline} />
              </IonButton>
             </IonItem>
            )}
 {data.date && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Date</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {formatLocalTime(
                data.date)}
              </IonLabel>
             </IonItem>
            )}
            {tx.status && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Status</IonLabel>
              <IonLabel
               color={statusColor}
               className={`tx-value ion-text-right`}
              >
               {tx.status}
              </IonLabel>
             </IonItem>
            )}
           </IonList>
          </IonCardContent>
         </IonCard>
        )}
        
        {type === "tv" && (
         <IonCard>
          <IonCardContent>
           <IonList>
            {tx.content?.transactions?.name && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Name</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.name}
              </IonLabel>
             </IonItem>
            )}

            {tx.content?.transactions?.phone && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Phone</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.phone}
              </IonLabel>
             </IonItem>
            )}

            {tx.content?.transactions?.product_name && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Product</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.product_name}
              </IonLabel>
             </IonItem>
            )}

            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Amount</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              ₦{formatNumber(tx.amount)}
             </IonLabel>
            </IonItem>

            {tx.content?.transactions?.status && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Status</IonLabel>
              <IonLabel
               color={statusColor}
               className={`tx-value ion-text-right`}
              >
               {tx.content.transactions.status}
              </IonLabel>
             </IonItem>
            )}
           </IonList>
          </IonCardContent>
         </IonCard>
        )}

        {type === "airtime" && (
         <IonCard>
          <IonCardContent>
           <IonList>
            {tx.content?.transactions?.unique_element && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Phone</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.unique_element}
              </IonLabel>
             </IonItem>
            )}

            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Product Name</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              {tx.content?.transactions?.product_name}
             </IonLabel>
            </IonItem>

            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Amount</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              ₦{formatNumber(tx.amount)}
             </IonLabel>
            </IonItem>
 {data.date && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Date</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {formatLocalTime(
                data.date)}
              </IonLabel>
             </IonItem>
            )}
            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Status</IonLabel>
             <IonLabel
              color={statusColor}
              className={`tx-value ion-text-right`}
             >
              {tx.content?.transactions?.status}
             </IonLabel>
            </IonItem>
           </IonList>
          </IonCardContent>
         </IonCard>
        )}

        {type === "data" && (
         <IonCard>
          <IonCardContent>
           <IonList>
            {tx.content?.transactions?.unique_element && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Phone</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.content.transactions.unique_element}
              </IonLabel>
             </IonItem>
            )}

            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Product Name</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              {tx.content?.transactions?.product_name}
             </IonLabel>
            </IonItem>

            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Amount</IonLabel>
             <IonLabel className="tx-value ion-text-right">
              ₦{formatNumber(tx.amount)}
             </IonLabel>
            </IonItem>
 {data.date && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Date</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {formatLocalTime(
                data.date)}
              </IonLabel>
             </IonItem>
            )}
            <IonItem lines="none" className="tx-row">
             <IonLabel className="tx-label">Status</IonLabel>
             <IonLabel
              color={statusColor}
              className={`tx-value ion-text-right`}
             >
              {tx.content?.transactions?.status}
             </IonLabel>
            </IonItem>
           </IonList>
          </IonCardContent>
         </IonCard>
        )}

        {type === "deposit" && tx && (
         <IonCard>
          <IonCardContent>
           <IonList>
            {/* ✅ SENDER INFO */}
            {(tx.data?.senderAccountName ||
             tx.data?.virtualAccount?.payerAccountName) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Sender Name</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.data?.senderAccountName ||
                tx.data?.virtualAccount?.payerAccountName}
              </IonLabel>
             </IonItem>
            )}

            {(tx.data?.senderAccountNumber ||
             tx.data?.virtualAccount?.payerAccountNumber) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Sender Account</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.data?.senderAccountNumber ||
                tx.data?.virtualAccount?.payerAccountNumber}
              </IonLabel>
              <IonButton
               fill="clear"
               slot="end"
               onClick={() =>
                copy(
                 tx.data?.senderAccountNumber ||
                  tx.data?.virtualAccount?.payerAccountNumber
                )
               }
              >
               <IonIcon icon={copyOutline} />
              </IonButton>
             </IonItem>
            )}

            {(tx.data?.senderBankName ||
             tx.data?.virtualAccount?.payerBankName) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Sender Bank</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {doSplit(tx.data?.senderBankName) ||
                doSplit(tx.data?.virtualAccount?.payerBankName)}
              </IonLabel>
             </IonItem>
            )}

            {/* ✅ RECIPIENT INFO */}
            {(tx.data?.recipientAccountName ||
             tx.data?.virtualAccount?.accountName) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Recipient</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.data?.recipientAccountName ||
                tx.data?.virtualAccount?.accountName}
              </IonLabel>
             </IonItem>
            )}

            {(tx.data?.recipientAccountNumber ||
             tx.data?.virtualAccount?.accountNumber) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Recipient Account</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.data?.recipientAccountNumber ||
                tx.data?.virtualAccount?.accountNumber}
              </IonLabel>
              <IonButton
               fill="clear"
               slot="end"
               onClick={() =>
                copy(
                 tx.data?.recipientAccountNumber ||
                  tx.data?.virtualAccount?.accountNumber
                )
               }
              >
               <IonIcon icon={copyOutline} />
              </IonButton>
             </IonItem>
            )}

            {(tx.data?.recipientBankName ||
             tx.data?.virtualAccount?.bankName) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Recipient Bank</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {doSplit(tx.data?.recipientBankName) ||
                doSplit(tx.data?.virtualAccount?.bankName)}
              </IonLabel>
             </IonItem>
            )}

            {/* ✅ AMOUNT */}
            {(data.amount ||
             tx.data?.destinationAmount ||
             tx.data?.amountReceived) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Amount</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {getCurrencySymbol(data.currency)}
               {formatNumber(
                data.amount ||
                 tx.data?.destinationAmount ||
                 tx.data?.amountReceived
               )}
              </IonLabel>
             </IonItem>
            )}

            {/* ✅ STATUS */}
            {tx.data?.status && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Status</IonLabel>
              <IonLabel
               color={statusColor}
               className={`tx-value ion-text-right`}
              >
               {tx.data.status}
              </IonLabel>
             </IonItem>
            )}

            {/* ✅ DATE */}
            {(data.date || tx.data?.createdAt || tx.data?.initiatedAt) && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Date</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {formatLocalTime(
                data.date || tx.data?.createdAt || tx.data?.initiatedAt
               )}
              </IonLabel>
             </IonItem>
            )}

            {/* ✅ REFERENCE */}
            {tx.data?.reference && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Reference</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {tx.data.reference}
              </IonLabel>
              <IonButton
               fill="clear"
               slot="end"
               onClick={() => copy(tx.data.reference)}
              >
               <IonIcon icon={copyOutline} />
              </IonButton>
             </IonItem>
            )}
           </IonList>
          </IonCardContent>
         </IonCard>
        )}

        <Ads />
        <p>&nbsp;</p>
       </>
      )}
      {!tx ||
       (Object.keys(tx).length === 0 &&
        !id?.startsWith("sl_") &&
        !id?.startsWith("send_") && (
          <IonCard>
          <IonCardContent>
        <IonList>
            {data?.title && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Title</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {data.title}
              </IonLabel>
             </IonItem>
            )}
              {data?.amount && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Amount</IonLabel>
              <IonLabel className="tx-value ion-text-right">
              {getCurrencySymbol(data.currency)} {formatNumber(data.amount)}
              </IonLabel>
             </IonItem>
            )}
           {data?.status && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Status</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {data.status}
              </IonLabel>
             </IonItem>
            )}
           {data?.date && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Date</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {formatLocalTime(
                data.date)}
              </IonLabel>
             </IonItem>
            )}
             {data?.our_ref && (
             <IonItem lines="none" className="tx-row">
              <IonLabel className="tx-label">Reference</IonLabel>
              <IonLabel className="tx-value ion-text-right">
               {data.our_ref}
              </IonLabel>
              <IonButton
               fill="clear"
               slot="end"
               onClick={() => copy(data.our_ref)}
              >
               <IonIcon icon={copyOutline} />
              </IonButton>
             </IonItem>
            )}
        </IonList>
        </IonCardContent>
        </IonCard>
        ))}

   {id && (id.startsWith("sl_") || id.startsWith("send_")) && (
  <IonCard>
    <IonCardContent>
      <IonList>

        {/* Title */}
        <IonItem lines="none" className="tx-row">
          <IonLabel className="tx-label">Title</IonLabel>
          <IonLabel className="tx-value ion-text-right">
            TRANSACTION DETAILS
          </IonLabel>
        </IonItem>

        {/* Sender */}
        {sInfo && (
          <IonItem lines="none" className="tx-row">
            <IonLabel className="tx-label">Sender</IonLabel>
            <IonLabel className="tx-value ion-text-right">
              {`${sInfo?.first_name?.toUpperCase()} ${sInfo?.last_name?.toUpperCase()}`}
            </IonLabel>
          </IonItem>
        )}

        {/* Beneficiary */}
        {rInfo && rInfo?.first_name?.toUpperCase() !== sInfo?.first_name?.toUpperCase() && (
          <IonItem lines="none" className="tx-row">
            <IonLabel className="tx-label">Beneficiary</IonLabel>
            <IonLabel className="tx-value ion-text-right">
              {`${rInfo?.first_name?.toUpperCase()} ${rInfo?.last_name?.toUpperCase()}`}
            </IonLabel>
          </IonItem>
        )}

        {/* Amount */}
        <IonItem lines="none" className="tx-row">
          <IonLabel className="tx-label">Amount</IonLabel>
          <IonLabel className="tx-value ion-text-right">
            {formatNumber(data?.amount)} {data?.currency}
          </IonLabel>
        </IonItem>

        {/* Reference */}
        <IonItem lines="none" className="tx-row">
          <IonLabel className="tx-label">Reference</IonLabel>
          <IonLabel className="tx-value ion-text-right">
            {id}
          </IonLabel>
          <IonButton fill="clear" slot="end" onClick={() => copy(id)}>
            <IonIcon icon={copyOutline} />
          </IonButton>
        </IonItem>

        {/* Date */}
        <IonItem lines="none" className="tx-row">
          <IonLabel className="tx-label">Date</IonLabel>
          <IonLabel className="tx-value ion-text-right">
            {formatLocalTime(data?.date)}
          </IonLabel>
        </IonItem>

        {/* Status */}
        <IonItem lines="none" className="tx-row">
          <IonLabel className="tx-label">Status</IonLabel>
          <IonLabel className="tx-value ion-text-right">
            {data?.status}
          </IonLabel>
        </IonItem>

        {/* Share Receipt Button */}
        <IonItem lines="none" className="ion-text-center">
          <IonButton color="secondary" expand="block" onClick={handleShare}>
            Share Receipt
          </IonButton>
        </IonItem>

      </IonList>
    </IonCardContent>
  </IonCard>
)}

     </>
    </IonContent>
   </IonPage>
  </>
 );
};

export default Tx;
