import React, { useState, useContext } from "react";
import {
 IonCard,
 IonCardContent,
 IonInput,
 IonButton,
 IonItem,
 IonLabel,
 IonSelect,
 IonSelectOption,
 IonSpinner,
 IonGrid,
 IonRow,
 IonCol,
 IonText,
 IonBadge,
} from "@ionic/react";
import {
 personOutline,
 lockClosedOutline,
 arrowBackOutline,
 alertCircle,
 checkmarkCircle,
} from "ionicons/icons";
import axios from "axios";
import { Context } from "../context/contex";

interface userInfoProps {
 id: number;
 email: string;
 phone: string;
 username: string | null;
 first_name: string;
 last_name: string;
 ngn_balance: string;
 //usd_balance: string;
 //eur_balance: string;
 email_verified: number;
 id_verified: number;
 withdrawal_bank_name: string | null;
 withdrawal_bank_code: string | null;
 withdrawal_bank_account: string | null;
 withdrawal_bank: string | null;
 photo: string | null;
 //nin: string | null;
 bvn: string | null;
 tx_pin: string | null;
 //card_holder_id: string | null;
 reg_date: number;
 country: string;
 state: string;
 city: string;
 dob: string;
 address: string;
 id_photo: string;
 postal_code: string;
 id_type: string;
 id_number: string;
 is_admin: number;
 is_banned: number;
 [key: string]: any;
kyc: number;

}



const UserSearchAndEdit: React.FC = () => {
 const [searchEmail, setSearchEmail] = useState("");
 const [user, setUser] = useState<userInfoProps | null>(null);
 const [editing, setEditing] = useState(false);
 const [form, setForm] = useState<Partial<userInfoProps>>({});
 const context = useContext(Context);
 if (!context) {
  return <div>Loading...</div>;
 }

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

 const handleSearch = async () => {
  if (!searchEmail.trim())
   return presentToast(
    "top",
    "Enter an email.",
    () => null,
    "danger",
    alertCircle
   );
  setBusy(true);

  const res = await apiRequest(
  "POST",
  "", //url
{
  action: "search_user_by_email",
    email: searchEmail,
},
  true,       // require auth
  false   // show success or error messages
  
) as any;

  if (res?.success) {
    setUser(res?.user);
    setForm(res?.user);
   } else {
    presentToast(
     "top",
     res.message || "User not found.",
     () => null,
     "danger",
     alertCircle
    );

   }

  setBusy(false);
 };

 const handleChange = (field: keyof userInfoProps, value: any) => {
  setForm((prev) => ({ ...prev, [field]: value }));
 };

 const handleSave = async () => {
  if (!userInfo) return;
  const token = await storage?.get(abr+"_auth_token");

  setBusy(true);
  
  try {
   const params = new URLSearchParams();
   params.append("action", "update_user_details");
   params.append("admin_id", userInfo.id.toString());

   // Append each field in form safely
   Object.entries(form).forEach(([key, val]) => {
    params.append(key, val !== undefined && val !== null ? String(val) : "");
   });
   const res = await axios.post(apiURL, params, {
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
     Authorization: `Bearer ${token}`,
    },
   });

   if (res.data?.success) {
    await handleSearch();
    presentToast(
     "top",
     res.data.message,
     () => null,
     "success",
     checkmarkCircle
    );
   } else {
    presentToast("top", res.data?.message, () => null, "danger", alertCircle);
   }

   setEditing(false);
  } catch (err) {
   console.error("Error saving:", err);
  } finally {
   setBusy(false);
  }
 };

 return (
  <>
   <IonGrid>
    <IonRow>
     <IonCol size="8">
      <IonInput
       type="text"
       placeholder="Enter user email or ID"
       value={searchEmail}
       onIonInput={(e) => setSearchEmail(e.detail.value!)}
       disabled={busy}
      />
     </IonCol>
     <IonCol size="4">
      <IonButton expand="block" onClick={handleSearch} disabled={busy}>
       {busy ? (
        <>
         <IonSpinner name="crescent" /> &nbsp; Searching...
        </>
       ) : (
        "Search"
       )}
      </IonButton>
     </IonCol>
    </IonRow>
   </IonGrid>

   {user && (
    <IonCard className="ion-padding">
     <IonCardContent>
      <IonGrid>
       <IonRow>
        <IonCol size="12">
         <IonInput
          label="First Name"
          labelPlacement="floating"
          value={form.first_name || ""}
          onIonInput={(e) => handleChange("first_name", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="Last Name"
          labelPlacement="floating"
          value={form.last_name || ""}
          onIonInput={(e) => handleChange("last_name", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="Email"
          labelPlacement="floating"
          type="email"
          value={form.email || ""}
          onIonInput={(e) => handleChange("email", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="Phone"
          labelPlacement="floating"
          value={form.phone || ""}
          onIonInput={(e) => handleChange("phone", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="NGN Balance"
          labelPlacement="floating"
          type="number"
          value={form.ngn_balance || ""}
          onIonInput={(e) => handleChange("ngn_balance", e.detail.value!)}
          readonly={!editing || !userInfo?.super_admin}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="Country"
          labelPlacement="floating"
          value={form.country || ""}
          onIonInput={(e) => handleChange("country", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="State"
          labelPlacement="floating"
          value={form.state || ""}
          onIonInput={(e) => handleChange("state", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="City"
          labelPlacement="floating"
          value={form.city || ""}
          onIonInput={(e) => handleChange("city", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="BVN"
          labelPlacement="floating"
          value={form.bvn || ""}
          readonly={true}
         />
        </IonCol>

        <IonCol size="12">
         <IonLabel className="ion-text-wrap">
          Email Verified{" "}
          <IonBadge color={form.email_verified == 1 ? "success" : "medium"}>
           {form.email_verified == 1 ? "Verified" : "Not Verified"}
          </IonBadge>
         </IonLabel>

         <IonSelect
          label="Email Verified"
          value={form.email_verified}
          onIonChange={(e) => handleChange("email_verified", e.detail.value)}
          interface="popover"
          disabled={!editing}
         >
          <IonSelectOption value={0}>No</IonSelectOption>
          <IonSelectOption value={1}>Yes</IonSelectOption>
         </IonSelect>
        </IonCol>

        <IonCol size="12">
         <IonLabel className="ion-text-wrap">
          ID Verified{" "}
          <IonBadge color={form.id_verified == 1 ? "success" : "medium"}>
           {form.id_verified == 1 ? "Verified" : "Not Verified"}
          </IonBadge>
         </IonLabel>

         <IonSelect
          label="ID Verified"
          interface="popover"
          value={form.id_verified || 0}
          onIonChange={(e) => handleChange("id_verified", e.detail.value)}
          disabled={!editing}
         >
          <IonSelectOption value={0}>No</IonSelectOption>
          <IonSelectOption value={1}>Yes</IonSelectOption>
         </IonSelect>
        </IonCol>

        <IonCol size="12">
         <IonLabel className="ion-text-wrap">
          Role{" "}
          <IonBadge color={form.is_admin == 1 ? "tertiary" : "medium"}>
           {form.is_admin == 1 ? "Admin" : "User"}
          </IonBadge>
         </IonLabel>

         <IonSelect
          label="Is Admin"
          interface="popover"
          value={form.is_admin || 0}
          onIonChange={(e) => handleChange("is_admin", e.detail.value)}
          disabled={!editing || !userInfo?.super_admin}
         >
          <IonSelectOption value={0}>No</IonSelectOption>
          <IonSelectOption value={1}>Yes</IonSelectOption>
         </IonSelect>
        </IonCol>

          <IonCol size="12">
         <IonLabel className="ion-text-wrap">
          Trader Type{" "}
          <IonBadge color={form.kyc == 1 ? "success" : "primary"}>
           {form.kyc == 1 ? "Bulk" : "Regular"}
          </IonBadge>
         </IonLabel>

         <IonSelect
          label="Trader Type"
          interface="popover"
          value={form.kyc || 0}
          onIonChange={(e) => handleChange("kyc", e.detail.value)}
          disabled={!editing}
         >
          <IonSelectOption value={0}>Regular</IonSelectOption>
          <IonSelectOption value={1}>Bulk</IonSelectOption>
         </IonSelect>
        </IonCol>

        <IonCol size="12">
         <IonLabel className="ion-text-wrap">
          Account Status{" "}
          <IonBadge color={form.is_banned == 1 ? "danger" : "success"}>
           {form.is_banned == 1 ? "Banned" : "Active"}
          </IonBadge>
         </IonLabel>

         <IonSelect
          label="Is Banned"
          interface="popover"
          value={form.is_banned || 0}
          onIonChange={(e) => handleChange("is_banned", e.detail.value)}
          disabled={!editing}
         >
          <IonSelectOption value={0}>No</IonSelectOption>
          <IonSelectOption value={1}>Yes</IonSelectOption>
         </IonSelect>
        </IonCol>

        <IonCol size="12">
         <IonInput
          label="Address"
          labelPlacement="floating"
          value={form.address || ""}
          onIonInput={(e) => handleChange("address", e.detail.value!)}
          readonly={!editing}
         />
        </IonCol>
       </IonRow>

       <IonRow className="ion-justify-content-end ion-padding-top">
        {!editing ? (
         <IonButton color="warning" onClick={() => setEditing(true)}>
          Edit User
         </IonButton>
        ) : (
         <>
          <IonButton
           color="medium"
           onClick={() => setEditing(false)}
           disabled={busy}
          >
           Cancel
          </IonButton>
          <IonButton color="success" onClick={handleSave} disabled={busy}>
           💾 Save Changes
          </IonButton>
         </>
        )}
       </IonRow>
      </IonGrid>
     </IonCardContent>
    </IonCard>
   )}
  </>
 );
};

export default UserSearchAndEdit;
