import {
  IonContent,
  IonButton,
  IonSegment,
  IonSegmentButton,
  IonLabel,
  IonModal,
  IonInput,
  IonSelect,
  IonSelectOption,
  IonGrid,
  IonRow,
  IonCol,
  IonHeader,
  IonToolbar,
  IonTitle,
IonIcon
} from "@ionic/react";
import { useEffect, useState, useContext } from "react";
import { Context } from "../context/contex";
import { copyOutline } from "ionicons/icons";

/* ================= TYPES ================= */

interface GiftCategory {
  id: number;
  name: string;
}

interface GiftCard {
  id: number;
  category: string;
  name: string;
  type: "ecode" | "physical";
  rate: string;
}

interface PendingSale {
  id: number;
  name: string;
  amount: string;
  rate: string;
  total: string;
  type: string;
  user_full_name: string;
  withdrawal_bank_name?: string;
  withdrawal_bank_account?: string;
  withdrawal_bank?: string;
  image: string;
}

/* ================= COMPONENT ================= */

const GiftCards: React.FC = () => {
   const [section, setSection] = useState<"manage" | "pay">("manage");
 const [modalVisible, setModalVisible] = useState(false);
const [cats, setCats] = useState<GiftCategory[]>([]);

  const [giftCards, setGiftCards] = useState<GiftCard[]>([]);
  const [sales, setSales] = useState<PendingSale[]>([]);

  const context = useContext(Context);
  if (!context) return null;

  const { apiRequest, settings, copy } = context;



  const [currentCard, setCurrentCard] = useState<{
    id?: number | string;
    category: string;
    name: string;
    type: "ecode" | "physical";
    rate: string;
  }>({
    category: "",
    name: "",
    type: "ecode",
    rate: "",
  });

  /* ================= FETCH ================= */

  const fetchCategories = async () => {
    const res = await apiRequest("POST", "", {
      action: "get_giftcard_categories",
    },
   false,
   false
   ) as any;
console.log("CATS", res)
    if (res?.success) setCats(res.data);
  };

  const fetchGiftCards = async () => {
    const res = await apiRequest("POST", "", {
      action: "get_all_gift_cards",
    },
   false,
   false
  ) as any;

    if (res?.success) setGiftCards(res.cards);
  };

  const fetchPendingSales = async () => {
    const res = await apiRequest("POST", "", {
      action: "get_pending_giftcard_sales",
    },
   false,
   false) as any;

    if (res?.success) setSales(res.data);
  };

  useEffect(() => {
    fetchCategories();
    fetchGiftCards();
    fetchPendingSales();
  }, []);


   const handleCardDelete = async (id: any) => {
    const res = await apiRequest(
      "POST",
      "",
      {
      action: "delete_gift_card", id 
      },
      true,
      true
    ) as any;
 if (res.success) {
      await fetchGiftCards();
     }

   };

   const handleCardEdit = (card: any) => {
  // Find the category object by name to get its id
  const selectedCategory = cats.find((c: any) => c.name === card.category);

  setCurrentCard({
   id: card.id || "",
   category: selectedCategory?.id?.toString() || "", // store category ID as string
   name: card.name || "",
   type: card.type || "ecode",
   rate: card.rate || "",
  });
  setModalVisible(true);
 };

  const handleCardCreate = () => {
  setCurrentCard({
   id: "",
   category: "",
   name: "",
   type: "ecode",
   rate: "",
  });
  setModalVisible(true);
 };

  const handleAction = async (id: any, actionType: any) => {
   const res = await apiRequest(
      "POST",
      "",
      {
      action: "handle_giftcard_sale_action",
      id: id,
      actionType: actionType,
      },
      true,
      true
    ) as any;
        if (res.success) fetchPendingSales();

  };

 

   const handleCardSubmit = async () => {
  const payload: any = {
    action: "save_gift_card",
  };

  Object.entries(currentCard).forEach(([key, val]) => {
    payload[key] = val;
  });

  try {
    const res = (await apiRequest(
      "POST",
      "",            // same endpoint
      payload,
      true,          // require auth
      true           // show success / error messages
    )) as any;

    if (res?.success) {
      setModalVisible(false);
      await fetchGiftCards();
    }
  } catch (err: any) {
    console.error("Submit error:", err?.message || err);
  }
};

  
  /* ================= RENDER ================= */

  return (
   <div>
   <IonSegment
  value={section}
  onIonChange={(e) => setSection(e.detail.value as "manage" | "pay")}
>
  <IonSegmentButton value="manage">
    <IonLabel>MANAGE GIFT CARDS</IonLabel>
  </IonSegmentButton>

  <IonSegmentButton value="pay">
    <IonLabel>PAY SELLERS</IonLabel>
  </IonSegmentButton>
</IonSegment>
{section === "manage" && (
  <div className="ion-margin-top">

    {/* Header row */}
    <div
      style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        marginBottom: 12,
      }}
    >
      <h4>Gift Card Manager</h4>

      <IonButton size="small" onClick={handleCardCreate}>
        Add Gift Card
      </IonButton>
    </div>

    {/* Table */}
    <IonGrid className="ion-no-padding">
      <IonRow className="ion-text-bold ion-padding-bottom">
        <IonCol size="1">ID</IonCol>
        <IonCol size="2">Category</IonCol>
        <IonCol size="3">Name</IonCol>
        <IonCol size="2">Type</IonCol>
        <IonCol size="2">Rate</IonCol>
        <IonCol size="2">Actions</IonCol>
      </IonRow>

      {giftCards.map((card) => (
        <IonRow key={card.id} className="ion-padding-vertical ion-border-top">
          <IonCol size="1">{card.id}</IonCol>
          <IonCol size="2">{card.category}</IonCol>
          <IonCol size="3">{card.name}</IonCol>
          <IonCol size="2">{card.type}</IonCol>
          <IonCol size="2">{card.rate}</IonCol>
          <IonCol size="2">
            <IonButton
              size="small"
              fill="outline"
              color="warning"
              onClick={() => handleCardEdit(card)}
            >
              Edit
            </IonButton>
            <IonButton
              size="small"
              fill="outline"
              color="danger"
              onClick={() => handleCardDelete(card.id)}
            >
              Delete
            </IonButton>
          </IonCol>
        </IonRow>
      ))}
    </IonGrid>
  </div>
)}
{section === "pay" && (
  <div className="ion-margin-top">
    <h4>Pending Gift Card Sales</h4>

    <IonGrid className="ion-no-padding">
      <IonRow className="ion-text-bold ion-padding-bottom">
        <IonCol size="2">User</IonCol>
        <IonCol size="2">Card</IonCol>
        <IonCol size="2">Image</IonCol>
        <IonCol size="1">Amount</IonCol>
        <IonCol size="1">Rate</IonCol>
        <IonCol size="1">Total</IonCol>
        <IonCol size="2">Bank</IonCol>
        <IonCol size="1">Actions</IonCol>
      </IonRow>

      {sales.length > 0 ? (
        sales.map((sale) => (
          <IonRow key={sale.id} className="ion-padding-vertical ion-border-top gc-table">
            <IonCol size="2">
              <small>{sale.user_full_name}</small>
            </IonCol>
            <IonCol size="2">{sale.name}</IonCol>
            <IonCol size="2">
              <img
                src={settings?.domain + sale.image}
                style={{ height: 40, borderRadius: 4 }}
              />
            </IonCol>
            <IonCol size="1">${Number(sale.amount).toLocaleString()}</IonCol>
            <IonCol size="1">{sale.rate}</IonCol>
            <IonCol size="1">₦{Number(sale.total).toLocaleString()}</IonCol>
            <IonCol size="2">
              <strong>{sale.withdrawal_bank_name || "-"}</strong>
              <br />
        <span
  style={{
    display: "inline-flex",
    alignItems: "center",
    gap: "6px",
    cursor: "pointer",
  }}
  onClick={() => copy(sale.withdrawal_bank_account || "")}
>
  {sale.withdrawal_bank_account || "-"}

  {sale.withdrawal_bank_account && (
    <IonIcon
      icon={copyOutline}
      style={{
        fontSize: "16px",
        opacity: 0.7,
      }}
    />
  )}
</span>

               <br />
              {sale.withdrawal_bank || "-"}
            </IonCol>
            <IonCol size="1">
              <IonButton
                size="small"
                color="success"
                onClick={() => handleAction(sale.id, "pay")}
              >
                Pay
              </IonButton>
              <IonButton
                size="small"
                color="danger"
                onClick={() => handleAction(sale.id, "reject")}
              >
                Reject
              </IonButton>
            </IonCol>
          </IonRow>
        ))
      ) : (
        <IonRow>
          <IonCol className="ion-text-center">
            No pending sales found.
          </IonCol>
        </IonRow>
      )}
    </IonGrid>
  </div>
)}

<IonModal isOpen={modalVisible} onDidDismiss={() => setModalVisible(false)}>
  <IonHeader>
    <IonToolbar>
      <IonTitle>
        {currentCard.id ? "Edit" : "Add"} Gift Card
      </IonTitle>
    </IonToolbar>
  </IonHeader>

  <IonContent className="ion-padding">
    <IonSelect
      label="Category"
      value={currentCard.category}
      onIonChange={(e) =>
        setCurrentCard((p) => ({ ...p, category: e.detail.value }))
      }
    >
      <IonSelectOption value="">Select Category</IonSelectOption>
      {cats.map((cat: any) => (
        <IonSelectOption key={cat.id} value={cat.id}>
          {cat.name}
        </IonSelectOption>
      ))}
    </IonSelect>

    <IonInput
      label="Name"
      value={currentCard.name}
      onIonChange={(e) =>
        setCurrentCard((p) => ({ ...p, name: e.detail.value! }))
      }
    />

    <IonSelect
      label="Type"
      value={currentCard.type}
      onIonChange={(e) =>
        setCurrentCard((p) => ({ ...p, type: e.detail.value }))
      }
    >
      <IonSelectOption value="ecode">eCode</IonSelectOption>
      <IonSelectOption value="physical">Physical</IonSelectOption>
    </IonSelect>

    <IonInput
      type="number"
      label="Rate"
      value={currentCard.rate}
      onIonChange={(e) =>
        setCurrentCard((p) => ({ ...p, rate: e.detail.value! }))
      }
    />

    <div className="ion-margin-top ion-text-right">
      <IonButton fill="outline" onClick={() => setModalVisible(false)}>
        Cancel
      </IonButton>
      <IonButton onClick={handleCardSubmit}>Save</IonButton>
    </div>
  </IonContent>
</IonModal>

   </div>
  );
};

export default GiftCards;
