import React, { useState, useContext, useEffect } from "react";

import {
 IonPage,

 IonRouterLink,
 IonButton,
 IonSelect,
 IonSelectOption,
 IonInput,
 IonList,
 IonItem,
 useIonRouter,
 IonLoading,
 IonAlert,
 IonRadio,
 IonRadioGroup,
 IonListHeader,
 IonLabel,
} from "@ionic/react";
import { Context } from "../../context/contex";
import AppShell from "../../components/Header";

import { alertCircle, checkmarkCircle } from "ionicons/icons";
import { formatNumber, getFirstWord, generateRequestId } from "../../utils";

const PayCableTv: React.FC = () => {
 const [vendors, setVendors] = useState<any>([]);
 const [tvVariations, setTvVariations] = useState<any>({});
 const [vendor, setVendor] = useState<any>({});
 const [decDetails, setDecDetails] = useState<any>({});
 const [buyDetails, setBuyDetails] = useState<any>({});
 const [packages, setPackages] = useState<any>({});
 const [decNumber, setDecNumber] = useState<string>("");
 const [type, setType] = useState<string>("renew");

 const [pinModal, setPinModal] = useState(false);
 const [cancel, setCancel] = useState(false);
 const context = useContext(Context);
 const router = useIonRouter();
 if (!context) {
  return <div>Loading...</div>;
 }

 const {
apiRequest,
  presentToast,
  userInfo,
  vtpassApiKey,
  vtpassBase,
  vtpassPubKey,
  vtpBalance,
  settings,
  reportLowBalance,
  storage,
  busy,
  setBusy
 } = context;

 const fetchServiceID = async (identifier: string) => {
  setBusy(true);
  try {
   const response = await fetch(
    vtpassBase + `services?identifier=${identifier}`,
    {
     method: "GET",
     headers: {
      "Content-Type": "application/json",
      "api-key": vtpassApiKey,
      "public-key": vtpassPubKey,
     },
    }
   );

   if (!response.ok) {
    throw new Error("Network response was not ok");
   }

   const result = await response.json();
   if (result.response_description === "000" && result.content) {
    console.log("VENDOR", result.content);
    setBusy(false);

    return result.content;
   } else {
    setBusy(false);

    return null;
   }
  } catch (error) {
   console.error("Error fetching service ID:", error);
   setBusy(false);

   return null;
  }
 };

 useEffect(() => {
  const fetchServices = async () => {
   try {
    const as = await fetchServiceID("tv-subscription");
    //   const ds = await fetchServiceID("data");

    if (as) {
     setVendors(as);
    }
   } catch (error) {
    console.error("Error fetching services:", error);
   }
  };
  fetchServices();
 }, [vtpassBase, vtpassApiKey, vtpassPubKey]);

 const getVariations = async (identifier: string) => {
  setBusy(true);
  setDecDetails({});
  setBuyDetails({});
  setPackages({});
  try {
   const response = await fetch(
    vtpassBase + `service-variations?serviceID=${identifier}`,
    {
     method: "GET",
     headers: {
      "Content-Type": "application/json",
      "api-key": vtpassApiKey,
      "public-key": vtpassPubKey,
     },
    }
   );

   if (!response.ok) {
    throw new Error("Network response was not ok");
   }

   const result = await response.json();
   if (result.response_description === "000" && result.content) {
    console.log("VAR", result.content.varations);
    setTvVariations(result.content.varations);
    setBusy(false);
   } else {
    console.error("Error fetching service variations:", result);
    setBusy(false);

    return null;
   }
  } catch (error) {
   console.error("Error getting variations:", error);
   setBusy(false);

   return null;
  }
 };

 useEffect(() => {
  if (!vendor.serviceID) {
   return;
  }
  getVariations(vendor.serviceID);
 }, [vendor.serviceID]);

 const verifyDecNumber = async () => {
  if (!decNumber) {
   presentToast(
    "top",
    `Smartcard number is empty.`,
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
  if (Object.keys(vendor).length === 0) {
   presentToast(
    "top",
    `Please choose a vendor.`,
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
  setDecDetails({});
  setBuyDetails({});
  const result = await apiRequest(
  "POST",
  "", //url
{
 action: "verify_profile_id",
     serviceID: vendor.serviceID,
     billersCode: String(decNumber),
     type: "null",
},
  false,       // require auth
  false   // show success or error messages
  
) as any;
 if (result?.success && result?.data && !result?.data.content?.error) {
    console.log("verified", result.data);
    setDecDetails(result.data.content);
   } else {
    console.log("not verified", result.data);
    presentToast(
     "top",
     result.data?.content?.error || result.message || "Verification failed",
     () => null,
     "danger",
     alertCircle
    );
   }
 
 };

 const handlePay = async (pin: number) => {
  if (cancel) return;
  if (!userInfo) {
   router.push("/login", "forward", "replace");
   return;
  }

  if (userInfo.tx_pin === null) {
   presentToast(
    "top",
    `Please set your transaction PIN first.`,
    () => null,
    "danger",
    alertCircle
   );
   router.push("/set-pin", "forward", "replace");
   return;
  }

  // Validation checks...
  if (Object.keys(vendor).length === 0) {
   presentToast(
    "top",
    "Please choose a vendor.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
  if (Object.keys(packages).length === 0) {
   presentToast(
    "top",
    "Please choose a package.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }

  if (Object.keys(decDetails).length === 0 && vendor.serviceID != "showmax") {
   presentToast(
    "top",
    "Please verify smartcard number first.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }

  if (+packages.variation_amount > +vtpBalance) {
   await reportLowBalance(+packages.variation_amount, "Vtpass", +vtpBalance);
   presentToast(
    "top",
    `Service not available at the moment.`,
    () => null,
    "danger",
    alertCircle
   );
   return;
  }

  if (+packages.variation_amount > +userInfo?.ngn_balance) {
   presentToast(
    "top",
    `You do not have sufficient funds in your wallet.`,
    () => null,
    "danger",
    alertCircle
   );
   router.push("/deposit", "forward", "replace");
   return;
  }

  if (+pin !== +userInfo.tx_pin) {
   presentToast("top", `Incorrect PIN!`, () => null, "danger", alertCircle);
   return;
  }
  setBuyDetails({});
  const id = generateRequestId();
  const token = await storage?.get("vin_auth_token");
  setBusy(true);

   const result = await apiRequest(
  "POST",
  "", //url
{
 action: "vtp_pay_tv",
     serviceID: vendor.serviceID,
     amount: packages.variation_amount,
     request_id: id,
     billersCode: decNumber,
     variation_code: packages.variation_code,
     phone: userInfo.phone,
     email: userInfo.email,
     subscription_type: type,
},
  true,       // require auth
  true   // show success or error messages
  
) as any;

 if (
    result?.success &&
    (result?.data.code === "000" || result?.data.code === "099")
   ) {
    const vtpassData = result.data;

    setBuyDetails(vtpassData);
    setVendor({});
    setDecDetails({});
    setPackages({});
    setTvVariations({});

    presentToast(
     "top",
     `Your purchase was successful. We will email you as soon as it is processed.`,
     () => null,
     "success",
     checkmarkCircle
    );

  
   } else {
    console.log("TV top-up failed:", result.data);
    presentToast(
     "top",
     `TV purchase failed: ${result.message}`,
     () => null,
     "danger",
     alertCircle
    );

   }

  await context.getUserInfo();
  await context.getTransactions();
 };

 return (
  <IonPage>
 
    <AppShell showBack={true} showLogo={false} title={'Pay for Tv'}>
    <IonLoading
     isOpen={busy}
     message="Please wait..."
     spinner="circles"
     className="custom-loading"
    />
    {vendors.length > 0 && (
  <div className="vendor-ui-header ion-text-center">
    <p>
      <strong>{settings?.app_name}</strong> lets you pay for TV subscription on{" "}
      {vendors.length} vendors. Choose your preferred vendor to get started.
    </p>
  </div>
)}

<div className="vendor-ui-grid">
  {vendors.map((v: any, i: number) => (
    <div
      key={i}
      className={`vendor-ui-card ${
        vendor?.serviceID === v.serviceID ? "active" : ""
      }`}
      onClick={() => setVendor(v)}
    >
      <img
        src={v.image}
        alt={v.name}
        className="vendor-ui-logo"
      />

      <div className="vendor-ui-name">
        {v.name}
      </div>
    </div>
  ))}
</div>


    {tvVariations.length > 0 && (
     <>
      <IonList
       className="ion-margin-bottom"
       style={{ border: "1px solid darkorange" }}
      >
       <IonItem>
        <IonSelect
         labelPlacement="floating"
         placeholder="Chose package"
         //  interface="popover"
         label="Chose package"
         value={packages}
         onIonChange={(e) => setPackages(e.detail.value)}
        >
         {tvVariations.map((plan: any, index: number) => (
          <IonSelectOption key={index} value={plan}>
           {plan.name}
          </IonSelectOption>
         ))}
        </IonSelect>
       </IonItem>
      </IonList>
     </>
    )}

    {tvVariations.length > 0 && vendor.serviceID != "showmax" && (
     <>
      <IonList
       className="ion-margin-bottom"
       style={{ border: "1px solid darkorange" }}
      >
       <IonItem>
        {/*HIDE ON SHOWMAX*/}
        <IonInput
         label={`Enter ${
          vendor.name != null && getFirstWord(vendor?.name)
         } Smart Card number`}
         labelPlacement="floating"
         placeholder="123456"
         value={decNumber}
         onIonInput={(e) => setDecNumber(e.detail.value || "")}
        ></IonInput>
       </IonItem>
      </IonList>
      <div className="ion-text-center">
       <IonButton color="danger" onClick={verifyDecNumber}>
        Verify smartcard number
       </IonButton>
      </div>
     </>
    )}

    {Object.keys(decDetails).length > 0 && vendor.serviceID != "showmax" && (
     <>
      <IonList>
       {decDetails.Customer_Name != null && (
        <IonItem>
         <IonLabel slot="start">Customer Name:</IonLabel>
         <IonLabel slot="end">{decDetails.Customer_Name}</IonLabel>
        </IonItem>
       )}
       {decDetails.Customer_Number != null && (
        <IonItem>
         <IonLabel slot="start">Customer Number:</IonLabel>
         <IonLabel slot="end">{decDetails.Customer_Number}</IonLabel>
        </IonItem>
       )}
       {decDetails.Customer_Type != null && (
        <IonItem>
         <IonLabel slot="start">Customer Type:</IonLabel>
         <IonLabel slot="end">{decDetails.Customer_Type}</IonLabel>
        </IonItem>
       )}
       {decDetails.Current_Bouquet != null && (
        <IonItem>
         <IonLabel slot="start">Current Bouquet:</IonLabel>
         <IonLabel slot="end">{decDetails.Current_Bouquet}</IonLabel>
        </IonItem>
       )}
       {decDetails.Current_Bouquet_Code != null && (
        <IonItem>
         <IonLabel slot="start">Current Bouquet Code:</IonLabel>
         <IonLabel slot="end">{decDetails.Current_Bouquet_Code}</IonLabel>
        </IonItem>
       )}
       {decDetails.Due_Date != null && (
        <IonItem>
         <IonLabel slot="start">Due Date:</IonLabel>
         <IonLabel slot="end">{decDetails.Due_Date}</IonLabel>
        </IonItem>
       )}
       {decDetails.Renewal_Amount != null && (
        <IonItem>
         <IonLabel slot="start">Renewal Amount:</IonLabel>
         <IonLabel slot="end">
          ₦{formatNumber(decDetails.Renewal_Amount)}
         </IonLabel>
        </IonItem>
       )}
       {decDetails.Status != null && (
        <IonItem>
         <IonLabel slot="start">Status:</IonLabel>
         <IonLabel slot="end">{decDetails.Status}</IonLabel>
        </IonItem>
       )}
       {decDetails.Smartcard_Number != null && (
        <IonItem>
         <IonLabel slot="start">Smartcard Number:</IonLabel>
         <IonLabel slot="end">{decDetails.Smartcard_Number}</IonLabel>
        </IonItem>
       )}
       {decDetails.Balance != null && (
        <IonItem>
         <IonLabel slot="start">Balance:</IonLabel>
         <IonLabel slot="end">₦{decDetails.Balance}</IonLabel>
        </IonItem>
       )}
      </IonList>
      <IonRadioGroup
       className="ion-margin-bottom"
       style={{ border: "1px solid darkorange" }}
       value={type}
       onIonChange={(e) => setType(e.detail.value)}
      >
       <IonListHeader>
        <IonLabel>What would you like to do?</IonLabel>
       </IonListHeader>
       <IonItem>
        <IonLabel>Renew Current Bouquet</IonLabel>

        <IonRadio
         slot="start"
         value="renew"
         aria-label="Renew Current Bouquet"
        ></IonRadio>
       </IonItem>

       <IonItem>
        <IonLabel>Change Current Bouquet</IonLabel>

        <IonRadio
         slot="start"
         value="change"
         aria-label="Change Current Bouquet"
        ></IonRadio>
       </IonItem>
      </IonRadioGroup>
     </>
    )}
    {Object.keys(packages).length > 0 && (
     <>
      {vendor.serviceID === "showmax" && (
       <IonList
        className="ion-margin-bottom"
        style={{ border: "1px solid darkorange" }}
       >
        <IonItem>
         {/*HIDE ON SHOWMAX*/}
         <IonInput
          label={`Enter ${
           vendor.name != null && getFirstWord(vendor?.name)
          } phone number`}
          labelPlacement="floating"
          placeholder="123456"
          value={decNumber}
          onIonInput={(e) => setDecNumber(e.detail.value || "")}
         ></IonInput>
        </IonItem>
       </IonList>
      )}

      <IonButton
       className="ion-margin-vertical"
       expand="block"
       onClick={() => setPinModal(true)}
      >
       PAY{" "}
       {Object.keys(packages).length > 0 &&
        "₦" + formatNumber(packages.variation_amount)}
      </IonButton>
     </>
    )}

    {Object.keys(buyDetails).length > 0 && (
     <>
      <h1 className="ion-text-center">PURCHASE DETAILS</h1>
      <IonList>
       <IonItem>
        <IonLabel slot="start">Product Name:</IonLabel>
        <IonLabel slot="start">
         {buyDetails.content.transactions.product_name}
        </IonLabel>
       </IonItem>
       <IonItem>
        <IonLabel slot="start">Amount:</IonLabel>
        <IonLabel slot="start">₦{formatNumber(buyDetails.amount)}</IonLabel>
       </IonItem>
       <IonItem>
        <IonLabel slot="start">Status:</IonLabel>
        <IonLabel slot="start">
         {buyDetails.content.transactions.status}
        </IonLabel>
       </IonItem>
      </IonList>
     </>
    )}

    <div className="ion-text-center">
     <p>
      Need help? <IonRouterLink routerLink="/contact">GET HELP</IonRouterLink>
     </p>
    </div>
    <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);
      handlePay(e.detail.data.values[0]);
     }}
     backdropDismiss={false}
    ></IonAlert>
   </AppShell>
  </IonPage>
 );
};

export default PayCableTv;
