import { useIonToast, useIonRouter } from "@ionic/react";

import {
 IonRow,
 IonCol,
 IonText,
 IonSpinner,
} from "@ionic/react";
export const hasCurrencyAndNetwork = (
 data: any[],
 currency: string,
 network: string
) => {
 return data.some(
  (item) => item.currency === currency && item.network === network
 );
};

export const hasCurrency = (data: any[], currency: string) => {
 return data.some((item) => item.currency === currency);
};

export function formatCardNumber(cardNumber: string): string {
 const formattedNumber = cardNumber.replace(/\D/g, ""); // Remove non-numeric characters
 const parts = [];
 for (let i = 0; i < formattedNumber.length; i += 4) {
  parts.push(formattedNumber.substring(i, i + 4));
 }
 return parts.join(" ");
}

export function formatNumber(
 number: string | number | undefined,
 min: number = 2,
 max: number = 2
): string {
 const parsed = Number(number);
 if (isNaN(parsed)) return "0.00";

 // Ensure min and max are within 0–20 and valid
 const safeMin = Math.max(0, Math.min(20, min));
 const safeMax = Math.max(safeMin, Math.min(20, max));

 return parsed.toLocaleString("en-US", {
  minimumFractionDigits: safeMin,
  maximumFractionDigits: safeMax,
 });
}

export const txColor = (statuses: string, flow: string = 'in') => {
 const status = statuses.toLowerCase();
 let txClass = "failed";
 switch (status) {
  case "complete":
  case "completed":
  case "success":
  case "successful":
    if(flow === 'in'){
txClass = "complete";
    }
    else {
      txClass = "complete-out";

    }
   
   break;
  case "failed":
  case "declined":
  case "error":
   txClass = "failed";
   break;
  case "pending":
  case "processing":
  case "in_progress":
   txClass = "pending";
   break;
 }
 return txClass;
};

interface GreetingProps {
 name: string;
}

export const Greeting: React.FC<GreetingProps> = ({ name }) => {
 const getGreeting = (): string => {
  const now = new Date();
  const hour = now.getHours();

  if (hour < 12) {
   return "Good morning";
  } else if (hour < 18) {
   return "Good afternoon";
  } else {
   return "Good evening";
  }
 };

 return (
  <div>
   {getGreeting()} <b>{name}</b> 👋
  </div>
 );
};

export function getPercentage(number: number, percent: number) {
 return (number * percent) / 100;
}

 export const formatLocalTime = (
  timestamp: number,
  mode: "full" | "date" | "time" | "short" = "full"
) => {
  const date = new Date(timestamp * 1000);

  // Default: full formatted date using locale
  if (mode === "full") {
    return date.toLocaleString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      hour12: true,
    });
  }

  // Short date: DD/MM/YYYY HH:mmam
  if (mode === "short") {
    const d = date.getDate().toString().padStart(2, "0");
    const m = (date.getMonth() + 1).toString().padStart(2, "0");
    const y = date.getFullYear();

    let hour = date.getHours();
    const minute = date.getMinutes().toString().padStart(2, "0");

    const ampm = hour >= 12 ? "pm" : "am";
    hour = hour % 12 || 12; // convert 0 → 12

    return `${d}/${m}/${y} ${hour}:${minute}${ampm}`;
  }

  // Date-only: DD/MM/YYYY
  if (mode === "date") {
    const d = date.getDate().toString().padStart(2, "0");
    const m = (date.getMonth() + 1).toString().padStart(2, "0");
    const y = date.getFullYear();
    return `${d}/${m}/${y}`;
  }

  // Time-only: HH:mmam
  if (mode === "time") {
    let hour = date.getHours();
    const minute = date.getMinutes().toString().padStart(2, "0");
    const ampm = hour >= 12 ? "pm" : "am";
    hour = hour % 12 || 12;
    return `${hour}:${minute}${ampm}`;
  }

  return "";
};


export const shortenAddress = (address: string) => {
 if (!address) return "";
 return `${address.slice(0, 4)}...${address.slice(-4)}`;
};

export const getQueryParam = (param: string) => {
 const urlParams = new URLSearchParams(window.location.search);
 return urlParams.get(param);
};

export const generateRequestId = () => {
 const now = new Date();
 const gmtPlusOneOffset = 60; // GMT+1 offset in minutes
 const gmtPlusOneDate = new Date(now.getTime() + gmtPlusOneOffset * 60 * 1000);

 const year = gmtPlusOneDate.getUTCFullYear();
 const month = String(gmtPlusOneDate.getUTCMonth() + 1).padStart(2, "0"); // Months are zero-based
 const day = String(gmtPlusOneDate.getUTCDate()).padStart(2, "0");
 const hour = String(gmtPlusOneDate.getUTCHours()).padStart(2, "0");
 const minutes = String(gmtPlusOneDate.getUTCMinutes()).padStart(2, "0");

 return `${year}${month}${day}${hour}${minutes}vnp`;
};

export const getFirstWord = (str: string) => {
 // Split the string by spaces and return the first element
 return str.split(" ")[0];
};

export const isValidYYYYMMDD = (s: string) => {
 const v = (s || "").trim();
 if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) return false; // format
 const [y, m, d] = v.split("-").map(Number);
 const dt = new Date(y, m - 1, d);
 // real date check (e.g., rejects 2024-02-30) and not in the future
 const isReal =
  dt.getFullYear() === y && dt.getMonth() === m - 1 && dt.getDate() === d;
 const notFuture = dt <= new Date();
 return isReal && notFuture;
};

export const parseError = (error: string) => {
 let msg;
 // console.log("FAILED:", error);

 if (error?.includes("Client error")) {
  const jsonString = error.substring(error.indexOf("{"));
  const json = JSON.parse(jsonString);
  msg = json.message || json.data?.message;
 } else if (error?.includes("quidax.com")) {
  msg =
   "There was a timeot error on our part. Please reload this page and try again.";
 } else {
  msg = error;
 }
 return msg;
};

export const getCurrencySymbol = (currency?: string): string => {
 if (!currency) return "₦"; // default to Naira

 switch (currency.toUpperCase()) {
  case "NGN":
   return "₦";
  case "USD":
   return "$";
   case "USDT":
   return "$";
   case "USDC":
   return "$";
  case "EUR":
   return "€";
  case "GBP":
   return "£";
  default:
   return currency.toUpperCase(); // fallback to Naira if unknown
 }
};

export const parseTxPayload = (payload: any) => {
  if (!payload) return null;

  try {
    if (typeof payload === "string") {
      return JSON.parse(payload.replace(/\\"/g, '"'));
    }
    return payload;
  } catch {
    return null;
  }
};

export const renderTx = (
  list: any[],
  loading: boolean,
  showMail: boolean = false,
  router: any
) => {
  if (loading) {
    return (
      <div className="ion-text-center ion-margin-top">
        <IonSpinner name="crescent" />
      </div>
    );
  }

  if (!list || 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) => {
    const isCrypto = tx.type === "crypto";
    const txs = isCrypto ? parseTxPayload(tx.payload) : null;

    return (
      <IonRow key={`tx_${tx.our_ref || index}`} className="ion-margin-vertical">
        {/* LEFT */}
        <IonCol className="tx-home" size="9">
          <IonText
            style={{ cursor: "pointer" }}
            onClick={() =>
              ( router.push(`/tx?tx=${tx.our_ref}`, "forward", "replace"))
            }
          >
            <b>{tx.title || "Transaction"}</b>
          </IonText>

          <br />

          <small>
            {showMail && tx.email ? `${tx.email} • ` : ""}
            {formatLocalTime(tx.date)}
          </small>
        </IonCol>

        {/* RIGHT */}
        <IonCol size="3" className="ion-text-right tx-home">
          <IonText>
            <b>
              {isCrypto && txs ? (
                txs.from_currency && txs.to_currency ? (
                  <>
                    {getCurrencySymbol(txs.from_currency)}
                    {formatNumber(txs.from_amount)} →{" "}
                    {getCurrencySymbol(txs.to_currency)}
                    {formatNumber(tx.amount, 6)}
                  </>
                ) : (
                  <>
                    {getCurrencySymbol(txs.currency)}
                    {formatNumber(txs.amount)}
                  </>
                )
              ) : (
                <>
                  {getCurrencySymbol(tx.currency)}
                  {formatNumber(tx.amount)}
                </>
              )}
            </b>
          </IonText>

          <br />

          <small className={txColor(tx.status, tx.flow)}>
            {tx.status}
          </small>
        </IonCol>
      </IonRow>
    );
  });
};
