import { useEffect, useState, useContext } from "react";
import { Context } from "../../context/contex";
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonSegment,
  IonSegmentButton,
  IonLabel,
 IonAlert,
  IonSelect,
  IonSelectOption,
  IonInput,
  IonButton,
  IonList,
  IonItem,
 
  IonLoading,
  IonBadge,
  IonAvatar,
  IonModal,
  IonButtons,
  IonIcon,
  IonGrid,
  IonRow,
  IonCol,
  IonCard,
  IonCardContent,
  IonText
} from "@ionic/react";
import {
 alertCircle,
 checkmarkCircle,
 copyOutline,
} from "ionicons/icons";
import { formatNumber, txColor, formatLocalTime } from "../../utils";
import AppShell from "../../components/Header";
import axios from "axios";

interface GiftCard {
  name: string;
  rate: number;
  logo?: string;
  currency?: string;
  id: string | number; 
}
interface Cat {
   name: string;
logo: string;
}

const GiftCard = () => {
 const [cats, setCats] = useState<any[]>([]);
 const [cat, setCat] = useState<Cat | null>(null);
 const [selectedCard, setSelectedCard] = useState<GiftCard | null>(null);
 const [pinModal, setPinModal] = useState(false);
 const [cancel, setCancel] = useState(false);


 const [type, setType] = useState(null);

 const [cards, setCards] = useState<any[]>([]);
 const [cardSales, setCardSales] = useState<any[]>([]);
const [showCategoryModal, setShowCategoryModal] = useState(false);

 const [section, setSection] = useState("sell");
 const [amount, setAmount] = useState("");
const [image, setImage] = useState<File | null>(null);
const [imageView, setImageView] = useState<string | null>(null);

  const naira = "₦";

 const context = useContext(Context);
 if (!context) {
  return <div>Loading...</div>;
 }
 const {
apiRequest,
busy,
setBusy,
  presentToast,
  userInfo,
 apiURL,
  settings,
  copy,
  abr,
  storage
 } = context;

const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  const file = e.target.files?.[0];

  if (file) {
    setImage(file);
    setImageView(URL.createObjectURL(file));
  }
};


 const getCats = async () => {
   const data = await apiRequest(
  "POST",
  "", //url
{
 action: "get_giftcard_categories",
},
  false,       // require auth
  false   // show success or error messages
  
) as any;
if(data?.success){
  setCats(data.data);
}
 
 };

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

 const getCards = async (category: string, logo: string) => {
  setCat(null);
  setCards([]);
  setSelectedCard(null);
  setAmount("");

     const data = await apiRequest(
  "POST",
  "", //url
{
 action: "get_giftcards_by_category",
     category: category,
     type: type,
},
  false,       // require auth
  false   // show success or error messages
  
) as any;
if(data?.success) {
    setCat({
     name: category,
     logo: logo,
    });
    setCards(data.data);
   // console.log("DATA:", data.data);
   }

 };

 const reset = () => {
  setCat(null);
  setCards([]);
  setSelectedCard(null);
  setAmount("");
  setType(null);
 };



  const sellGiftCard = async () => {
    if (cancel) return;

  if (!image) {
     presentToast(
       "top",
       `Please upload gift card image or screenshot`,
       () => null,
       "danger",
       alertCircle
      );
 
   return;
  }

  if (!amount) {
    presentToast(
       "top",
       `Invalid amount`,
       () => null,
       "danger",
       alertCircle
      );

   return;
  }
  if (!selectedCard) {
    presentToast(
       "top",
       `Invalid card selection.`,
       () => null,
       "danger",
       alertCircle
      );

   return;
  }

  if (!userInfo?.withdrawal_bank_account) {
    presentToast(
       "top",
       `Please set your bank account from the settings page.`,
       () => null,
       "danger",
       alertCircle
      );

   return;
  }

  if (userInfo?.id_verified !== 1) {
    presentToast(
       "top",
       `You must pass KYC to proceed.`,
       () => null,
       "danger",
       alertCircle
      );
  
   return;
  }
    const token = await storage?.get(abr+"_auth_token");

   setBusy(true);
 
   const formData = new FormData();
   formData.append("card-image", image);
   formData.append("card-type", String(type));
   formData.append("amount", amount);
   formData.append("cid", String(selectedCard.id));
   formData.append("action", "sell_giftcard");
 
   try {
    const response = await axios.post(apiURL, formData, {
     headers: {
      "Content-Type": "multipart/form-data",
      Authorization: `Bearer ${token}`,
     },
    });
   // console.log("RES", response.data);
    if (response.data.success) {
     reset();
     await getCardSales(userInfo?.id);
    presentToast(
       "top",
       `Your giftcard sale is processing. We will email you about the status.`,
       () => null,
       "success",
       checkmarkCircle
      );
    } else {
       presentToast(
       "top",
       response.data.message,
       () => null,
       "danger",
       alertCircle
      );
  
    }
   } catch (error) {
    alert("An error occurred during submission.");
    console.error("Submission error", error);
   }
   setBusy(false);
  };

 const getCardSales = async (id: string | number) => {

  const data = await apiRequest(
  "POST",
  "", //url
{
action: "get_user_giftcards_sales",
     id: id,
},
  false,       // require auth
  false   // show success or error messages
  
) as any;
if(data?.success){
     setCardSales(data.data);

}

 };

 useEffect(() => {
  if (!userInfo?.id) return;
  getCardSales(userInfo?.id);
 }, [userInfo]);

 return (
<IonPage>
  <AppShell showBack showLogo={false} title="Gift Cards">

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

    {/* TOP SEGMENT */}
    <IonSegment
      value={section}
      onIonChange={(e) => setSection(e.detail.value as "sell" | "sold")}
      className="gc-segment"
    >
      <IonSegmentButton value="sell">
        <IonLabel>Sell Cards</IonLabel>
      </IonSegmentButton>
      <IonSegmentButton value="sold">
        <IonLabel>History</IonLabel>
      </IonSegmentButton>
    </IonSegment>

    {/* ================= SELL ================= */}
    {section === "sell" && (
      <IonContent>
        <div className="gc-container">

          {/* HEADER */}
          <div className="gc-header">
            <h2>Sell Gift Cards</h2>
            <p>Exchange your gift cards for instant cash</p>
          </div>

          {/* STEP 1 — CARD TYPE */}
          <div className="gc-section">
            <IonSelect
              label="Card Type"
              placeholder="Choose card type"
              interface="action-sheet"
              onIonChange={(e) => setType(e.detail.value)}
            >
              <IonSelectOption value="physical">Physical Card</IonSelectOption>
              <IonSelectOption value="ecode">E-Code</IonSelectOption>
            </IonSelect>
          </div>

          {/* STEP 2 — CATEGORY */}
      {type && (
  <div className="gc-section">
    <h4 className="gc-section-title">Select Category</h4>

    <IonItem
      button
      detail
      lines="none"
      className="gc-dropdown-trigger"
      onClick={() => setShowCategoryModal(true)}
    >
      {cat ? (
        <>
          <IonAvatar slot="start">
            <img src={cat.logo} alt={cat.name} />
          </IonAvatar>
          <IonLabel>{cat.name}</IonLabel>
        </>
      ) : (
        <IonLabel color="medium">Choose category</IonLabel>
      )}
    </IonItem>
  </div>
)}


          {/* STEP 3 — CARD */}
          {cards.length > 0 && (
            <div className="gc-section">
              <h4 className="gc-section-title">Select Gift Card</h4>

              <div className="gc-grid">
                {cards.map((card, i) => (
                  <div
                    key={i}
                    className={`gc-tile ${selectedCard?.name === card.name ? "active" : ""}`}
                    onClick={() => setSelectedCard(card)}
                  >
                    <img src={card.logo || "/assets/images/card-placeholder.png"}/>
                    <div>{card.name}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* STEP 4 — RATE + AMOUNT */}
          {selectedCard && (
            <div className="gc-section">
              <div className="gc-rate">
                <span>Rate</span>
                <strong>{naira}{selectedCard.rate} / USD</strong>
              </div>

              <IonInput
                label="USD Amount"
                type="number"
                placeholder="Enter amount"
                value={amount}
                onIonInput={(e) => setAmount(e.detail.value as string)}
              />

              <IonInput
                label="You Receive"
                readonly
                value={Number(amount) * selectedCard.rate || ""}
              />
            </div>
          )}

          {/* STEP 5 — IMAGE */}
          {selectedCard && (
            <div className="gc-section">
              <h4 className="gc-section-title">Upload Card Image</h4>

              {imageView && (
                <img src={imageView} className="gc-preview" />
              )}

              <input
                type="file"
                accept="image/*"
                onChange={handleImageChange}
                className="gc-file-input"
              />
            </div>
          )}

          {/* ACTIONS */}
          {Number(amount) > 0 && (
            <div className="gc-actions">
              <IonButton expand="block" color="primary"   onClick={() => setPinModal(true)}>
                Submit Trade
              </IonButton>

              <IonButton expand="block" fill="clear" onClick={reset}>
                Cancel
              </IonButton>
            </div>
          )}

          {/* HELP */}
          <div className="gc-help">
            Need help? <a href="/contact">Contact Support</a>
          </div>

        </div>
      </IonContent>
    )}

    {/* ================= SOLD ================= */}
  {section === "sold" && (
  <IonContent>
    <IonGrid className="gc-history-wrapper">
      {cardSales.length > 0 ? (
        cardSales.map((tx, i) => (
          <IonRow key={i}>
            <IonCol size="12">
              <IonCard className="gc-history-card">
                <IonCardContent className="gc-history-content">

                  {/* LEFT: IMAGE */}
                  <div className="gc-history-image">
                    <img
                      src={settings?.domain +'/'+ tx.image || "/assets/images/card-placeholder.png"}
                      alt={tx.name}
                    />
                  </div>

                  {/* CENTER: DETAILS */}
                  <div className="gc-history-details">
                    <h3 className="gc-history-title">{tx.name}</h3>
                    <p className="gc-history-meta">
                      {naira}
                      {formatNumber(tx.total)}
                      {tx.created_at && (
                        <>
                          {" • "}
                          {formatLocalTime(tx.created_at, "date")}
                        </>
                      )}
                    </p>
                  </div>

                  {/* RIGHT: STATUS */}
                  <div className="gc-history-status">
                    <span className={`gc-status-pill ${txColor(tx.status)}`}>
                      {tx.status}
                    </span>
                  </div>

                </IonCardContent>
              </IonCard>
            </IonCol>
          </IonRow>
        ))
      ) : (
        <IonRow>
          <IonCol size="12" className="ion-text-center ion-margin-top">
            <IonText color="medium">
              <p>No transactions yet</p>
            </IonText>
          </IonCol>
        </IonRow>
      )}
    </IonGrid>
  </IonContent>
)}

<IonModal
  isOpen={showCategoryModal}
  onDidDismiss={() => setShowCategoryModal(false)}
>
  <IonHeader>
    <IonToolbar>
      <IonTitle>Select Category</IonTitle>
      <IonButtons slot="end">
        <IonButton onClick={() => setShowCategoryModal(false)}>
          Close
        </IonButton>
      </IonButtons>
    </IonToolbar>
  </IonHeader>

  <IonContent>
    <IonList>
      {cats.map((c, i) => (
        <IonItem
          key={i}
          button
          onClick={() => {
            setCat(c);
            getCards(c.name, c.logo);
            setShowCategoryModal(false);
          }}
        >
          <IonAvatar slot="start">
            <img src={c.logo} alt={c.name} />
          </IonAvatar>

          <IonLabel>{c.name}</IonLabel>

          {cat?.name === c.name && (
            <IonIcon
              slot="end"
              icon={checkmarkCircle}
              color="primary"
            />
          )}
        </IonItem>
      ))}
    </IonList>
  </IonContent>
</IonModal>
<IonAlert
     isOpen={pinModal}
     header="Authorize Transaction"
     subHeader="Enter your PIN to authorize this transaction."
     className="pin-alert"
     buttons={[
      {
       text: "Cancel",
       cssClass: "alert-button-cancel",
       handler: () => {
        setCancel(true);
       },
      },
      {
       text: "Proceed",
       cssClass: "alert-button-confirm",

       handler: () => setCancel(false),
      },
     ]}
     inputs={[
      {
       type: "password",
       placeholder: "Enter PIN",
       attributes: {
        inputmode: "numeric",
        maxLength: 4,
       },
      },
     ]}
     onDidDismiss={(e) => {
      setPinModal(false);
     sellGiftCard();
     }}
     backdropDismiss={false}
    ></IonAlert>
  </AppShell>
</IonPage>


 );
};

export default GiftCard;
