import {
 IonPage,
 IonHeader,
 IonToolbar,
 IonButtons,
 IonBackButton,
 IonTitle,
 IonContent,
 IonIcon,
 IonText,
 IonCard,
 IonCardContent,
 IonList,
 IonItem,
 IonLabel,
 IonButton,
 IonGrid,
 IonRow,
 IonCol,
 IonLoading,
} from "@ionic/react";
import {
 arrowBackOutline,
 checkmarkCircleOutline,
 closeCircleOutline,
 timeOutline,
 copyOutline,
} from "ionicons/icons";
import { formatNumber, formatLocalTime, shortenAddress } from "../utils";
import Ads from "./Ads";

interface TransactionDetailsProps {
 tx: any;
 type: string;
 id?: string | null;
 data?: any;
 sInfo?: any;
 rInfo?: any;
 busy?: boolean;
 handleShare?: () => void;
 copy: (text: string) => void;
}

const TransactionDetails: React.FC<TransactionDetailsProps> = ({
 tx,
 type,
 id,
 data,
 sInfo,
 rInfo,
 busy,
 handleShare,
 copy,
}) => {
 const status =
  tx?.content?.transactions?.status?.toLowerCase() ||
  tx?.status?.toLowerCase() ||
  "pending";

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

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

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

 return (
  <IonPage>
   <IonHeader>
    <IonToolbar
     color="darkblue"
     className="darkblue-header ion-padding-horizontal"
    >
     <IonButtons slot="start">
      <IonBackButton text="" icon={arrowBackOutline} defaultHref="/" />
     </IonButtons>
     <IonTitle>Transaction Details</IonTitle>
    </IonToolbar>
   </IonHeader>

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

   <IonContent fullscreen className="ion-padding transaction-page">
    {tx && Object.keys(tx).length > 0 ? (
     <>
      <div className="ion-text-center ion-margin-bottom">
       <IonIcon
        icon={statusIcon}
        color={statusColor}
        style={{ fontSize: "65px" }}
       />
       <IonText color={statusColor}>
        <h2 className="ion-margin-top">{statusText}</h2>
       </IonText>
      </div>

      {/* 🎓 Education */}
      {type === "education" && (
       <IonCard>
        <IonCardContent>
         <IonList>
          <IonItem>
           <IonLabel>
            <strong>Name:</strong> {tx.content?.transactions?.product_name}
           </IonLabel>
          </IonItem>

          {tx.content?.transactions?.quantity && (
           <IonItem>
            <IonLabel>
             <strong>Quantity:</strong> {tx.content.transactions.quantity}
            </IonLabel>
           </IonItem>
          )}

          {tx.content?.transactions?.unit_price && (
           <IonItem>
            <IonLabel>
             <strong>Unit Price:</strong> ₦
             {formatNumber(tx.content.transactions.unit_price)}
            </IonLabel>
           </IonItem>
          )}

          {tx.content?.transactions?.convinience_fee !== null && (
           <IonItem>
            <IonLabel>
             <strong>Convenience Fee:</strong> ₦
             {formatNumber(tx.content.transactions.convinience_fee)}
            </IonLabel>
           </IonItem>
          )}

          <IonItem>
           <IonLabel>
            <strong>Total Amount:</strong> ₦{formatNumber(tx.amount)}
           </IonLabel>
          </IonItem>

          <IonItem>
           <IonLabel>
            <strong>Status:</strong> {tx.content?.transactions?.status}
           </IonLabel>
          </IonItem>

          {tx.tokens &&
           tx.tokens.length > 0 &&
           tx.tokens.map((pin: string, i: number) => (
            <IonItem key={i}>
             <IonLabel>
              <strong>PIN {i + 1}:</strong> {pin}
             </IonLabel>
             <IonButton fill="clear" slot="end" onClick={() => copy(pin)}>
              <IonIcon icon={copyOutline} />
             </IonButton>
            </IonItem>
           ))}

          {tx.cards &&
           tx.cards.length > 0 &&
           tx.cards.map((pin: any, i: number) => (
            <IonItem key={i}>
             <IonLabel className="ion-text-wrap">
              <strong>Card {i + 1}</strong>
              <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>
           ))}

          {tx.purchased_code && (
           <IonItem>
            <IonLabel>
             <strong>PIN:</strong> {getToken(tx.purchased_code)}
            </IonLabel>
            <IonButton
             fill="clear"
             slot="end"
             onClick={() => copy(getToken(tx.purchased_code))}
            >
             <IonIcon icon={copyOutline} />
            </IonButton>
           </IonItem>
          )}
         </IonList>
        </IonCardContent>
       </IonCard>
      )}

      {/* ⚡ Electricity */}
      {type === "electricity" && (
       <IonCard>
        <IonCardContent>
         <IonList>
          {tx.customerName && (
           <IonItem>
            <IonLabel>
             <strong>Name:</strong> {tx.customerName}
            </IonLabel>
           </IonItem>
          )}
          {tx.Name && (
           <IonItem>
            <IonLabel>
             <strong>Name:</strong> {tx.Name}
            </IonLabel>
           </IonItem>
          )}
          {tx.customerAddress && (
           <IonItem>
            <IonLabel>
             <strong>Address:</strong> {tx.customerAddress}
            </IonLabel>
           </IonItem>
          )}
          {tx.Address && (
           <IonItem>
            <IonLabel>
             <strong>Address:</strong> {tx.Address}
            </IonLabel>
           </IonItem>
          )}

          <IonItem>
           <IonLabel>
            <strong>Amount:</strong> ₦{formatNumber(tx.amount)}
           </IonLabel>
          </IonItem>

          {tx.balance && (
           <IonItem>
            <IonLabel>
             <strong>Balance:</strong> {tx.balance}
            </IonLabel>
           </IonItem>
          )}
          {tx.purchased_code && (
           <IonItem>
            <IonLabel>
             <strong>PIN:</strong> {getToken(tx.purchased_code)}
            </IonLabel>
            <IonButton
             fill="clear"
             slot="end"
             onClick={() => copy(getToken(tx.purchased_code))}
            >
             <IonIcon icon={copyOutline} />
            </IonButton>
           </IonItem>
          )}
          {tx.units && (
           <IonItem>
            <IonLabel>
             <strong>Units:</strong> {tx.units}
            </IonLabel>
           </IonItem>
          )}
          {tx.MeterNumber && (
           <IonItem>
            <IonLabel>
             <strong>Meter Number:</strong> {tx.MeterNumber}
            </IonLabel>
           </IonItem>
          )}
          {tx.tariff && (
           <IonItem>
            <IonLabel>
             <strong>Tariff:</strong> {tx.tariff}
            </IonLabel>
           </IonItem>
          )}
          {tx.content?.transactions?.status && (
           <IonItem>
            <IonLabel>
             <strong>Status:</strong> {tx.content.transactions.status}
            </IonLabel>
           </IonItem>
          )}
         </IonList>
        </IonCardContent>
       </IonCard>
      )}

      {/* 📱 Airtime */}
      {type === "airtime" && (
       <IonCard>
        <IonCardContent>
         <IonList>
          {tx.content?.transactions?.unique_element && (
           <IonItem>
            <IonLabel>
             <strong>Phone:</strong> {tx.content.transactions.unique_element}
            </IonLabel>
           </IonItem>
          )}
          <IonItem>
           <IonLabel>
            <strong>Product Name:</strong>{" "}
            {tx.content?.transactions?.product_name}
           </IonLabel>
          </IonItem>
          <IonItem>
           <IonLabel>
            <strong>Amount:</strong> ₦{formatNumber(tx.amount)}
           </IonLabel>
          </IonItem>
          <IonItem>
           <IonLabel>
            <strong>Status:</strong> {tx.content?.transactions?.status}
           </IonLabel>
          </IonItem>
         </IonList>
        </IonCardContent>
       </IonCard>
      )}

      {/* 🌐 Data */}
      {type === "data" && (
       <IonCard>
        <IonCardContent>
         <IonList>
          {tx.content?.transactions?.unique_element && (
           <IonItem>
            <IonLabel>
             <strong>Phone:</strong> {tx.content.transactions.unique_element}
            </IonLabel>
           </IonItem>
          )}
          <IonItem>
           <IonLabel>
            <strong>Product Name:</strong>{" "}
            {tx.content?.transactions?.product_name}
           </IonLabel>
          </IonItem>
          <IonItem>
           <IonLabel>
            <strong>Amount:</strong> ₦{formatNumber(tx.amount)}
           </IonLabel>
          </IonItem>
          <IonItem>
           <IonLabel>
            <strong>Status:</strong> {tx.content?.transactions?.status}
           </IonLabel>
          </IonItem>
         </IonList>
        </IonCardContent>
       </IonCard>
      )}

      {/* 📺 TV */}
      {type === "tv" && (
       <IonCard>
        <IonCardContent>
         <IonList>
          {tx.content?.transactions?.name && (
           <IonItem>
            <IonLabel>
             <strong>Name:</strong> {tx.content.transactions.name}
            </IonLabel>
           </IonItem>
          )}
          {tx.content?.transactions?.phone && (
           <IonItem>
            <IonLabel>
             <strong>Phone:</strong> {tx.content.transactions.phone}
            </IonLabel>
           </IonItem>
          )}
          <IonItem>
           <IonLabel>
            <strong>Product Name:</strong>{" "}
            {tx.content?.transactions?.product_name}
           </IonLabel>
          </IonItem>
          <IonItem>
           <IonLabel>
            <strong>Amount:</strong> ₦{formatNumber(tx.amount)}
           </IonLabel>
          </IonItem>
          <IonItem>
           <IonLabel>
            <strong>Status:</strong> {tx.content?.transactions?.status}
           </IonLabel>
          </IonItem>
         </IonList>
        </IonCardContent>
       </IonCard>
      )}

      {/* 💰 Crypto */}
      {type === "crypto" && (
       <IonCard>
        <IonCardContent>
         <IonList>
          {tx.currency && (
           <IonItem>
            <IonLabel>
             <strong>Currency:</strong> {tx.currency?.toUpperCase()}
            </IonLabel>
           </IonItem>
          )}
          {tx.to_currency && (
           <IonItem>
            <IonLabel>
             <strong>To Currency:</strong> {tx.to_currency?.toUpperCase()}
            </IonLabel>
           </IonItem>
          )}
          <IonItem>
           <IonLabel>
            <strong>Amount:</strong> {data?.amount}
           </IonLabel>
          </IonItem>
          {tx.txid && (
           <IonItem>
            <IonLabel>
             <strong>Transaction Hash:</strong> {shortenAddress(tx.txid)}
            </IonLabel>
            <IonButton fill="clear" slot="end" onClick={() => copy(tx.txid)}>
             <IonIcon icon={copyOutline} />
            </IonButton>
           </IonItem>
          )}
          {tx.status && (
           <IonItem>
            <IonLabel>
             <strong>Status:</strong> {tx.status}
            </IonLabel>
           </IonItem>
          )}
         </IonList>
        </IonCardContent>
       </IonCard>
      )}

      {/* 🤝 P2P / Send */}
      {id && (id.startsWith("sl_") || id.startsWith("send_")) && (
       <IonGrid>
        <IonRow>
         <IonCol>
          <h2 className="ion-text-center">TRANSACTION DETAILS</h2>
         </IonCol>
        </IonRow>
        <IonRow>
         <IonCol size="6">
          <IonLabel>Sender:</IonLabel>
         </IonCol>
         <IonCol size="6">
          <IonLabel>
           {`${sInfo?.first_name?.toUpperCase()} ${sInfo?.last_name?.toUpperCase()}`}
          </IonLabel>
         </IonCol>
        </IonRow>
        <IonRow>
         <IonCol size="6">
          <IonLabel>Beneficiary:</IonLabel>
         </IonCol>
         <IonCol size="6">
          <IonLabel>
           {`${rInfo?.first_name?.toUpperCase()} ${rInfo?.last_name?.toUpperCase()}`}
          </IonLabel>
         </IonCol>
        </IonRow>
        <IonRow>
         <IonCol size="6">
          <IonLabel>Amount:</IonLabel>
         </IonCol>
         <IonCol size="6">
          <IonLabel>
           {formatNumber(data?.amount)} {data?.currency}
          </IonLabel>
         </IonCol>
        </IonRow>
        <IonRow>
         <IonCol size="6">
          <IonLabel>REF:</IonLabel>
         </IonCol>
         <IonCol size="6">
          <IonLabel>{id}</IonLabel>
         </IonCol>
        </IonRow>
        <IonRow>
         <IonCol size="6">
          <IonLabel>Date:</IonLabel>
         </IonCol>
         <IonCol size="6">
          <IonLabel>{formatLocalTime(data?.date)}</IonLabel>
         </IonCol>
        </IonRow>
        <IonRow>
         <IonCol size="6">
          <IonLabel>Status:</IonLabel>
         </IonCol>
         <IonCol size="6">
          <IonLabel>{data?.status}</IonLabel>
         </IonCol>
        </IonRow>
        <IonRow className="ion-text-center">
         <IonCol size="12">
          <IonButton color="secondary" onClick={handleShare}>
           Share Receipt
          </IonButton>
         </IonCol>
        </IonRow>
       </IonGrid>
      )}

      <Ads />
     </>
    ) : (
     <IonText color="medium">
      <p className="ion-text-center ion-margin-top">
       No transaction details for this transaction type.
      </p>
     </IonText>
    )}
   </IonContent>
  </IonPage>
 );
};

export default TransactionDetails;
