import React, { useContext, useEffect, useState } from "react";
import {
 IonPage,
 IonHeader,
 IonToolbar,
 IonTitle,
 IonContent,
 IonGrid,
 IonRow,
 IonCol,
 IonCard,
 IonCardHeader,
 IonCardTitle,
 IonCardContent,
 IonText,
 IonButtons,
 IonBackButton,
 IonLoading,
 IonList,
 IonItem,
 IonMenu,
 IonMenuToggle,
 IonLabel,
 IonIcon,
 useIonRouter,
 IonInput,
 IonButton,
 IonMenuButton,
 useIonAlert,
 IonBadge,
 IonSelect,
 IonSelectOption,
 IonSegment,
 IonSegmentButton,
 IonTextarea
} from "@ionic/react";
import {
 alertCircle,
 homeOutline,
 settingsOutline,
 barChartOutline,
 arrowBackOutline,
 menuOutline,
 checkmarkCircle,
} from "ionicons/icons";
import {
 formatNumber,
} from "../../utils/index";
import { Context } from "../../context/contex";
import UserSearchAndEdit from "../../components/searchUsers";
import UserListPaginated from "../../components/UserList";
import axios from "axios";
import GiftCards from "../../components/GiftCards";
import AdminPromos from "../../components/AdminPromos";

interface settingsProps {
 //card_deposit_pcnt: number;
 //card_deposit_cap: number;
 ngn_bank_deposit_fee: number;
 //ngn_bank_deposit_cap: number; //unused
 app_name: string;
 admin_email: string;
 smtp_host: string;
 smtp_email: string;
 smtp_password: string;
 //local_transfer_fee: number;
 //withdrawal_fee: number;
 //usd_buy_rate: number | 0;
 //usd_sell_rate: number | 0;
 //visa_card_creation_fee: number;
 domain: string;
 //card_withdrawal_fee: string;
 //card_funding_fee: string;
 vtp_base: string;
 vtp_api: string;
 vtp_pub: string;
 api_url: string;
 contact_email: string;
 contact_phone: string | number;
 contact_address: string;
 facebook: string | null;
 x: string | null;
 instagram: string | null;
 youtube: string | null;
 whatsapp: string | null;
 quidax_sell_rate: number;
 quidax_buy_rate: number;
 enable_topup: number;
 enable_bills: number;
 enable_giftcard: number;
 enable_crypto: number;
 //enable_banking: number;
 ref_bonus: number;
 ref_spend: number;
 
}

interface StatsProps {
 total_users: number;
 total_verified: number;
 total_unverified: number;
 total_users_balance: number;
 total_usd_balance: number;
 total_spent: number;
  total_ngn_tx: number;

}

interface ADS {
 id: number;
 image: string;
 link: string;
}

const Admin: React.FC = () => {
 const context = useContext(Context);
 const router = useIonRouter();
 const [activeMenu, setActiveMenu] = useState("users");
 const [ads, setAds] = useState<any[]>([]);
 const [link, setLink] = useState("#");
 const [image, setImage] = useState<File | null>(null);
const [activeUsersTab, setActiveUsersTab] = useState("list");
const [activeNTab, setActiveNTab] = useState("email");
const [emailSubject, setEmailSubject] = useState<string>("");
const [emailMessage, setEmailMessage] = useState<string>("");

const [notifyMessage, setNotifyMessage] = useState<string>("");
 const [presentAlert] = useIonAlert();

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

 const {
  userInfo,
  apiURL,
  busy,
  setBusy,
  settings,
  presentToast,
  vtpBalance,
  quidaxBalance,
  apiRequest,
  abr,
  storage,
  
 } = context;

 const [stats, setStats] = useState<StatsProps | null>(null);

 const [form, setForm] = useState<settingsProps>({
  admin_email: "",
  smtp_host: "",
  smtp_email: "",
  smtp_password: "",
  ngn_bank_deposit_fee: 0,
  app_name: "",
  domain: "",
  vtp_base: "",
  vtp_api: "",
  vtp_pub: "",
  api_url: "",
  contact_email: "",
  contact_phone: "",
  contact_address: "",
  facebook: "",
  x: "",
  instagram: "",
  youtube: "",
  whatsapp: "",
  quidax_sell_rate: 0,
  quidax_buy_rate: 0,
   enable_topup: 1,
 enable_bills: 1,
 enable_giftcard: 1,
 enable_crypto: 1,
 ref_bonus: 0,
 ref_spend: 0,
 });

 useEffect(() => {
  if (!settings) return;
  setForm(settings);
 }, [settings]);

 const handleSubmitSettings = async (e: React.FormEvent) => {
  e.preventDefault();

  if (!userInfo || !userInfo.id) {
   return presentToast(
    "top",
    "Unable to verify admin identity. Please log in again.",
    () => null,
    "danger",
    alertCircle
   );
  }

  const payload = new URLSearchParams();
  payload.append("action", "update_settings");
  payload.append("user_id", userInfo.id.toString());

  // Append all form values
  Object.entries(form).forEach(([key, val]) => {
   payload.append(key, val);
  });
  const token = await storage?.get(abr+"_auth_token");

  setBusy(true);
  try {
   const res = await axios.post(apiURL, payload, {
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
     Authorization: `Bearer ${token}`,
    },
   });

   if (res.data.success) {
    context.getSettings();
    presentToast(
     "top",
     res.data.message,
     () => null,
     "success",
     checkmarkCircle
    );
   } else {
    presentToast("top", res.data.message, () => null, "danger", alertCircle);
   }
  } catch (error) {
   console.error("Settings update error:", error);
   presentToast(
    "top",
    "Something went wrong while updating settings.",
    () => null,
    "danger",
    alertCircle
   );
  }
  setBusy(false);
 };

 const fetchAdminStats = async () => {
  if (!userInfo) {
   return;
  }
   const res = await apiRequest(
  "POST",
  "", //url
  {
    action: "get_user_stats",
   
  },
  true,       // require auth
  false     // show success or error messages
) as any;


  if (res?.success) {
   setStats(res?.stats);
   //console.log("Admin stats:", res.data.data);
  } else {
   console.error(res.message);
  }
 };

 useEffect(() => {
  fetchAdminStats();
 }, [userInfo]);

 const handleChange = (e: CustomEvent) => {
  const target = e.target as HTMLInputElement;
  setForm((prev) => ({
   ...prev,
   [target.name]: target.value,
  }));
 };

 const getAds = async () => {
  setBusy(true);
  try {
   const response = await fetch(apiURL, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({ action: "get_ads" }),
   });

   if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
   }

   const data = await response.json();
   if (data.error) {
    console.error("Error:", data.error);
   } else {
    setAds(data);

    //   console.log("Fetched settings:", data);
   }
  } catch (error: any) {
   console.error("Error:", error?.message);
  }
  setBusy(false);
 };

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

 const handleCreateAds = async (e: React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  const token = await storage?.get(abr+"_auth_token");

  if (!image) {
   presentToast("top", "Select an image.", () => null, "danger", alertCircle);
   return;
  }

  try {
   setBusy(true);

const formData = new FormData();
formData.append("action", "create_ad");
formData.append("link", link);
formData.append("image", image as Blob);

const res = await axios.post(apiURL, formData, {
  headers: {
    Authorization: `Bearer ${token}`,
  },
});

   if (res.data.success) {
    setImage(null);
    setLink("#");
    await getAds();

    presentToast("top", "Ad created.", () => null, "success", checkmarkCircle);
   } else {
    presentToast(
     "top",
     res.data.message || "Ad could not be created.",
     () => null,
     "danger",
     alertCircle
    );
   }
  } catch (error) {
   console.error("Ad creation error:", error);
   presentToast(
    "top",
    "Something went wrong while creating the ad.",
    () => null,
    "danger",
    alertCircle
   );
  } finally {
   setBusy(false);
  }
 };

 const handleDeleteAds = async (id: number) => {
  presentAlert({
   header: "Delete Ad?",
   message: "This ad will be permanently deleted.",
   buttons: [
    {
     text: "Cancel",
     role: "cancel",
    },
    {
     text: "Delete",
     role: "confirm",
     cssClass: "danger",
     handler: async () => {
      setBusy(true);
      try {
       const res = await axios.post(
        apiURL,
        new URLSearchParams({ action: "delete_ad", id: id.toString() }),
        { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
       );

       presentAlert({
        header: res.data.success ? "Deleted" : "Error",
        message: res.data.message,
        buttons: ["OK"],
       });

       if (res.data.success) getAds();
      } catch (err) {
       console.error(err);
       presentAlert({
        header: "Error",
        message: "Something went wrong while deleting the ad.",
        buttons: ["OK"],
       });
      }
      setBusy(false);
     },
    },
   ],
  });
 };

 const sendEmailBroadcast = async () => {
   await apiRequest(
  "POST",
  "", //url
  {
    action: "queue_broadcast",
      type: "email",
      subject: emailSubject,
      message: emailMessage
   
  },
  true,       // require auth
  true     // show success or error messages
) as any;
 
};

const sendNotificationBroadcast = async () => {
   await apiRequest(
  "POST",
  "", //url
  {
    action: "queue_broadcast",
      type: "notification",
      message: notifyMessage,
       subject: emailSubject,
   
  },
  true,       // require auth
  true     // show success or error messages
) as any;
 
};

const statCards = [
  {
    title: "Total Users",
    value: stats?.total_users ?? 0,
    prefix: "",
  },
  {
    title: "Total Verified Users",
    value: stats?.total_verified ?? 0,
    prefix: "",
  },
  {
    title: "Total NGN Balance",
    value: stats?.total_users_balance
      ? formatNumber(stats.total_users_balance)
      : "0",
    prefix: "₦",
  },
  {
    title: "Vtpass Balance",
    value: vtpBalance ? formatNumber(vtpBalance) : "0",
    prefix: "₦",
  },
  {
    title: "Quidax Balance",
    value: quidaxBalance ? formatNumber(quidaxBalance) : "0",
    prefix: "₦",
  },
  {
    title: "NGN Transactions",
    value: stats?.total_ngn_tx
      ? formatNumber(stats.total_ngn_tx)
      : "0",
    prefix: "₦",
  },
];


 return (
  <>
 
{userInfo && userInfo.is_admin == 1 &&
<>
  <IonMenu type="overlay" contentId="admin-content" side="end">
    <IonHeader>
     <IonToolbar>
      <IonTitle>Menu</IonTitle>
     </IonToolbar>
    </IonHeader>
    <IonContent>
     <IonList>
      {/* Home */}
      <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => router.push("/", "forward")}>
        <IonIcon icon={homeOutline} slot="start" />
        <IonLabel>Home</IonLabel>
       </IonItem>
      </IonMenuToggle>
      <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => router.push("/admin-tx", "forward")}>
        <IonIcon icon={barChartOutline} slot="start" />
        <IonLabel>Transactions</IonLabel>
       </IonItem>
      </IonMenuToggle>
      <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => setActiveMenu("users")}>
        <IonIcon icon={barChartOutline} slot="start" />
        <IonLabel>Manage Users</IonLabel>
       </IonItem>
      </IonMenuToggle>


       <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => setActiveMenu("broadcast")}>
        <IonIcon icon={barChartOutline} slot="start" />
        <IonLabel>Send Broadcasts</IonLabel>
       </IonItem>
      </IonMenuToggle>

      <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => setActiveMenu("ads")}>
        <IonIcon icon={barChartOutline} slot="start" />
        <IonLabel>Manage Ads</IonLabel>
       </IonItem>
      </IonMenuToggle>
       <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => setActiveMenu("cards")}>
        <IonIcon icon={barChartOutline} slot="start" />
        <IonLabel>Manage Gifcards</IonLabel>
       </IonItem>
      </IonMenuToggle>
 <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => setActiveMenu("promo")}>
        <IonIcon icon={barChartOutline} slot="start" />
        <IonLabel>Manage Promos</IonLabel>
       </IonItem>
      </IonMenuToggle>
      {/* Settings */}
      {userInfo && userInfo.super_admin === 1 &&
      <IonMenuToggle autoHide={true}>
       <IonItem button onClick={() => setActiveMenu("settings")}>
        <IonIcon icon={settingsOutline} slot="start" />
        <IonLabel>Settings</IonLabel>
       </IonItem>
      </IonMenuToggle>
}
     </IonList>
    </IonContent>
   </IonMenu>
   <IonPage id="admin-content">
    
    <IonHeader>
     <IonToolbar className="nobg ion-padding-horizontal">
      <IonButtons slot="start">
       <IonBackButton
        text=""
        icon={arrowBackOutline}
        defaultHref="/"
       ></IonBackButton>
      </IonButtons>

      <IonTitle>Admin</IonTitle>

      <IonButtons slot="end">
       <IonMenuButton autoHide={false}>
        <IonIcon icon={menuOutline} />
       </IonMenuButton>
      </IonButtons>
     </IonToolbar>
    </IonHeader>

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

    <IonContent fullscreen className="ion-padding ion-content-bg">
      {activeMenu === 'broadcast' &&
 <>

<IonSegment value={activeNTab} onIonChange={(e: any) => setActiveNTab(e.detail.value)}>
  <IonSegmentButton value="email">
    <IonLabel>Email Broadcast</IonLabel>
  </IonSegmentButton>

  <IonSegmentButton value="notification">
    <IonLabel>Push Notification</IonLabel>
  </IonSegmentButton>
</IonSegment>

<div className="ion-margin-top">

  {/* EMAIL BROADCAST */}
  {activeNTab === "email" && (
    <IonCard>
      <IonCardHeader><IonCardTitle>Send Email Broadcast</IonCardTitle></IonCardHeader>
      <IonCardContent>
        <IonInput
          label="Subject"
          labelPlacement="stacked"
          onIonInput={(e) => setEmailSubject(e.detail.value!)}
        />
        <IonTextarea
          label="Message"
          labelPlacement="stacked"
          autoGrow
          onIonInput={(e) => setEmailMessage(e.detail.value!)}
        />
        <IonButton
          expand="block"
          className="ion-margin-top"
          onClick={sendEmailBroadcast}
        >
          Queue Email Broadcast
        </IonButton>
      </IonCardContent>
    </IonCard>
  )}

  {/* NOTIFICATION BROADCAST */}
  {activeNTab === "notification" && (
    <IonCard>
      <IonCardHeader><IonCardTitle>Send Notification Broadcast. Keep it under 150 characters or less.</IonCardTitle></IonCardHeader>
      <IonCardContent>
          <IonInput
          label="Subject"
          labelPlacement="stacked"
          onIonInput={(e) => setEmailSubject(e.detail.value!)}
        />
         <p>{emailSubject.length} / short is better</p>
        <IonTextarea
          label="Notification Message"
          labelPlacement="stacked"
          autoGrow
          onIonInput={(e) => setNotifyMessage(e.detail.value!)}
          maxlength={150}
        />
        <p>{notifyMessage.length} / 150</p>
        <IonButton
          expand="block"
          className="ion-margin-top"
          onClick={sendNotificationBroadcast}
        >
          Queue Notification Broadcast
        </IonButton>
      </IonCardContent>
    </IonCard>
  )}

</div>

</>
      }
       {activeMenu === "promo" && (
<AdminPromos/>
           )}
           {activeMenu === "cards" && (
<GiftCards/>
           )}
     {activeMenu === "ads" && (
      <div className="ion-margin-top">
       <IonText color="primary">
        <h4 className="fw-bold">📢 Manage Ads</h4>
       </IonText>

       {/* Create Ad Form */}
       <form onSubmit={handleCreateAds}>
        <IonGrid>
         <IonRow>
          <IonCol size="12" size-md="6">
           <IonItem>
            <IonInput
             label="Ad Link"
             labelPlacement="floating"
             type="text"
             value={link}
             onIonInput={(e) => setLink(e.detail.value!)}
            />
           </IonItem>
          </IonCol>

          <IonCol size="12" size-md="6">
           <IonItem lines="none">
            <IonLabel position="stacked">Ad Image</IonLabel>
            <input
             type="file"
             accept="image/*"
             onChange={(e) => {
              const file = (e.target as HTMLInputElement).files?.[0] ?? null;
              setImage(file);
             }}
             style={{
              width: "100%",
              padding: "10px",
              border: "1px solid var(--ion-color-medium)",
              borderRadius: "8px",
              background: "var(--ion-color-light)",
             }}
            />
           </IonItem>
          </IonCol>

          <IonCol size="12" className="ion-text-end ion-margin-top">
           <IonButton
            type="submit"
            color="primary"
            shape="round"
            disabled={busy}
           >
            {busy ? "Uploading..." : "Upload Ad"}
           </IonButton>
          </IonCol>
         </IonRow>
        </IonGrid>
       </form>

       {/* Ads List */}
       <IonGrid className="ion-margin-top">
        <IonRow>
         {ads.length === 0 && (
          <IonCol size="12" className="ion-text-center ion-padding">
           <IonText color="medium">No ads available yet.</IonText>
          </IonCol>
         )}

         {ads.map((ad: any) => (
          <IonCol size="12" size-md="3" key={ad.id}>
           <IonCard>
            <img
             src={settings?.domain + ad.image}
             alt="ad"
             style={{
              width: "100%",
              height: "120px",
              objectFit: "cover",
              borderTopLeftRadius: "8px",
              borderTopRightRadius: "8px",
             }}
            />
            <IonCardContent>
             <IonText>
              <p className="ion-no-margin">
               <strong>Link: </strong>
               <a
                href={ad.link}
                target="_blank"
                rel="noreferrer"
                style={{
                 color: "var(--ion-color-primary)",
                 textDecoration: "none",
                }}
               >
                View
               </a>
              </p>
             </IonText>

             <div className="ion-text-end ion-margin-top">
              <IonButton
               color="danger"
               size="small"
               onClick={() => handleDeleteAds(ad.id)}
              >
               Delete
              </IonButton>
             </div>
            </IonCardContent>
           </IonCard>
          </IonCol>
         ))}
        </IonRow>
       </IonGrid>
      </div>
     )}

     {activeMenu === "settings" && (
      <>
       {userInfo?.is_admin ? (
        <>
         <IonText color="primary">
          <h3 className="fw-bold ion-margin-bottom">⚙️ Admin Settings</h3>
         </IonText>

         <form onSubmit={handleSubmitSettings}>
          <IonGrid>
           <IonRow>
          
 <IonCol size="12" size-md="6">
   <IonLabel className="ion-text-wrap">
          Topup{" "}
          <IonBadge color={form.enable_topup == 1 ? "success" : "medium"}>
           {form.enable_topup == 1 ? "Enabled" : "Disabled"}
          </IonBadge>
         </IonLabel>
  <IonItem>
        

         <IonSelect
          label="Enable Topup"
          interface="popover"
          name="enable_topup"
          value={form.enable_topup || 0}
          onIonChange={handleChange}
        
         >
          <IonSelectOption value={0}>Disable</IonSelectOption>
          <IonSelectOption value={1}>Enable</IonSelectOption>
         </IonSelect>
         </IonItem>
        </IonCol>

         <IonCol size="12" size-md="6">
           <IonLabel className="ion-text-wrap">
          Bills{" "}
          <IonBadge color={form.enable_bills == 1 ? "success" : "medium"}>
           {form.enable_bills == 1 ? "Enabled" : "Disabled"}
          </IonBadge>
         </IonLabel>
          <IonItem>
        

         <IonSelect
          label="Enable Bill Payment"
          interface="popover"
          name="enable_bills"
          value={form.enable_bills || 0}
          onIonChange={handleChange}
        
         >
          <IonSelectOption value={0}>Disable</IonSelectOption>
          <IonSelectOption value={1}>Enable</IonSelectOption>
         </IonSelect>
         </IonItem>
        </IonCol>

         <IonCol size="12" size-md="6">
           <IonLabel className="ion-text-wrap">
          Gift Card{" "}
          <IonBadge color={form.enable_giftcard == 1 ? "success" : "medium"}>
           {form.enable_giftcard == 1 ? "Enabled" : "Disabled"}
          </IonBadge>
         </IonLabel>
          <IonItem>
        

         <IonSelect
          label="Enable Virtual Card"
          interface="popover"
          name="enable_giftcard"
          value={form.enable_giftcard || 0}
          onIonChange={handleChange}
        
         >
          <IonSelectOption value={0}>Disable</IonSelectOption>
          <IonSelectOption value={1}>Enable</IonSelectOption>
         </IonSelect>
         </IonItem>
        </IonCol>

         <IonCol size="12" size-md="6">
         <IonLabel className="ion-text-wrap">
          Crypto{" "}
          <IonBadge color={form.enable_crypto == 1 ? "success" : "medium"}>
           {form.enable_crypto == 1 ? "Enabled" : "Disabled"}
          </IonBadge>
         </IonLabel>
 <IonItem>
         <IonSelect
          label="Enable Crypto"
          interface="popover"
          name="enable_crypto"
          value={form.enable_crypto || 0}
          onIonChange={handleChange}
        
         >
          <IonSelectOption value={0}>Disable</IonSelectOption>
          <IonSelectOption value={1}>Enable</IonSelectOption>
         </IonSelect>
         </IonItem>
        </IonCol>

     
            <IonCol size="12" size-md="6">
             <IonItem>
              <IonInput
               label="App Name"
               labelPlacement="floating"
               name="app_name"
               value={form.app_name}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            <IonCol size="12" size-md="6">
             <IonItem>
              <IonInput
               label="Domain"
               labelPlacement="floating"
               name="domain"
               value={form.domain}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            <IonCol size="12" size-md="6">
             <IonItem>
              <IonInput
               label="Admin Email"
               labelPlacement="floating"
               type="email"
               name="admin_email"
               value={form.admin_email}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            {/* SMTP SETTINGS */}
            <IonCol size="12" className="ion-margin-top">
             <IonText color="primary">
              <h5 className="fw-bold">📧 SMTP Configuration</h5>
             </IonText>
            </IonCol>

            <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               label="SMTP Host"
               labelPlacement="floating"
               name="smtp_host"
               value={form.smtp_host}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               label="SMTP Email"
               labelPlacement="floating"
               type="email"
               name="smtp_email"
               value={form.smtp_email}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               label="SMTP Password"
               labelPlacement="floating"
               type="text"
               name="smtp_password"
               value={form.smtp_password}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            {/* RATES */}
            <IonCol size="12" className="ion-margin-top">
             <IonText color="primary">
              <h5 className="fw-bold">💱 Rates & Fees</h5>
             </IonText>
            </IonCol>

           

  <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               type="number"
               label="Referral bonus"
               labelPlacement="floating"
               name="ref_bonus"
               value={form.ref_bonus}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

             <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               type="number"
               label="Referral spend threshold"
               labelPlacement="floating"
               name="ref_spend"
               value={form.ref_spend}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

         
            {/* QUIDAX RATES */}
            <IonCol size="12" className="ion-margin-top">
             <IonText color="primary">
              <h5 className="fw-bold">🪙 Quidax Rates</h5>
             </IonText>
            </IonCol>

            <IonCol size="12" size-md="6">
             <IonItem>
              <IonInput
               type="number"
               label="Quidax Buy Rate to Add (NGN)"
               labelPlacement="floating"
               name="quidax_buy_rate"
               value={form.quidax_buy_rate}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            <IonCol size="12" size-md="6">
             <IonItem>
              <IonInput
               type="number"
               label="Quidax Sell Rate to Subtract (NGN)"
               labelPlacement="floating"
               name="quidax_sell_rate"
               value={form.quidax_sell_rate}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            {/* API CONFIG */}
            <IonCol size="12" className="ion-margin-top">
             <IonText color="primary">
              <h5 className="fw-bold">🔗 API Configuration</h5>
             </IonText>
            </IonCol>

            {["api_url", "vtp_base", "vtp_api", "vtp_pub"].map((field) => (
             <IonCol size="12" size-md="6" key={field}>
              <IonItem>
               <IonInput
                label={field.replace("_", " ").toUpperCase()}
                labelPlacement="floating"
                name={field}
                value={form[field as keyof settingsProps] ?? ""}
                onIonInput={handleChange}
               />
              </IonItem>
             </IonCol>
            ))}

            {/* CONTACT */}
            <IonCol size="12" className="ion-margin-top">
             <IonText color="primary">
              <h5 className="fw-bold">📞 Contact Information</h5>
             </IonText>
            </IonCol>

            <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               type="email"
               label="Contact Email"
               labelPlacement="floating"
               name="contact_email"
               value={form.contact_email}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               label="Contact Phone"
               labelPlacement="floating"
               name="contact_phone"
               value={form.contact_phone}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            <IonCol size="12" size-md="4">
             <IonItem>
              <IonInput
               label="Contact Address"
               labelPlacement="floating"
               name="contact_address"
               value={form.contact_address}
               onIonInput={handleChange}
              />
             </IonItem>
            </IonCol>

            {/* SOCIAL LINKS */}
            <IonCol size="12" className="ion-margin-top">
             <IonText color="primary">
              <h5 className="fw-bold">🌐 Social Links</h5>
             </IonText>
            </IonCol>

            {["facebook", "x", "instagram", "youtube", "whatsapp"].map(
             (field) => (
              <IonCol size="12" size-md="6" key={field}>
               <IonItem>
                <IonInput
                 label={`${field.toUpperCase()} URL`}
                 labelPlacement="floating"
                 name={field}
                 value={form[field as keyof settingsProps] ?? ""}
                 onIonInput={handleChange}
                />
               </IonItem>
              </IonCol>
             )
            )}
           </IonRow>
          </IonGrid>

          <div className="ion-text-end ion-margin-top">
           <IonButton type="submit" color="primary" shape="round">
            💾 Update Settings
           </IonButton>
          </div>
         </form>
        </>
       ) : (
        <IonText color="medium">
         <p className="ion-text-center">
          You do not have permission to view this page.
         </p>
        </IonText>
       )}
      </>
     )}

     {activeMenu === "users" && (
      <div>
       {userInfo?.is_admin ? (
        <>
         <div className=" ion-margin-vertical">
          <IonText color="dark">
           <h2 className="fw-bolder ion-text-uppercase">Manage Users</h2>
          </IonText>

        <IonGrid className="ion-margin-top">
  <IonRow className="ion-justify-content-center ion-padding-bottom">
    {statCards.map((card, index) => (
    <IonCol key={index} size="12" size-md="3">
  <IonCard className="stat-card-dark">
    <IonCardHeader>
      <IonCardTitle>{card.title}</IonCardTitle>
    </IonCardHeader>

    <IonCardContent>
      <h2 className="fw-bolder stat-card-value">
        {card.prefix}
        {card.value}
      </h2>
    </IonCardContent>
  </IonCard>
</IonCol>

    ))}
  </IonRow>
</IonGrid>

        <IonSegment
  value={activeUsersTab}
onIonChange={(e: CustomEvent) => setActiveUsersTab(e.detail.value)}

  className="ion-margin-top"
>
  <IonSegmentButton value="list">
    <IonLabel>All Users</IonLabel>
  </IonSegmentButton>

  <IonSegmentButton value="search">
    <IonLabel>Search / Edit</IonLabel>
  </IonSegmentButton>
</IonSegment>

<div className="ion-margin-top">
  {activeUsersTab === "list" && (
    <UserListPaginated />
  )}

  {activeUsersTab === "search" && (
    <UserSearchAndEdit />
  )}
</div>

         </div>
        </>
       ) : (
        <IonText color="medium">
         <p className="ion-text-center ion-margin-top">
          You do not have permission to view this page.
         </p>
        </IonText>
       )}
      </div>
     )}
     <p>&nbsp;</p>
    </IonContent>
    
   </IonPage>
   </>
}
  </>
 );
};

export default Admin;
