"use client";
import { useEffect, useState } from "react";
import { sendRequest } from "../constants";
import PaymentForm from "../components/wallet/PaymentForm";
import { BASE_URL } from "@/constants";

import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import Link from "next/link";
import { redirect } from "next/navigation";
import GemsGrid, { Pack, packs } from "../components/wallet/GemsGrid";
import NotAvailable from "../components/ui/NotAvailable";
export interface AuthState {
  user: User; // adjust type as needed
  status: string;
}

const Page = () => {
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);
  if (!user) {
    redirect("/");
  }
  const [tab, setTab] = useState("deposit");
  const [amount, setAmount] = useState("10");
  const [message, setMessage] = useState("");
  const [selected, setSelected] = useState("");
  const [depositAmount, setDepositAmount] = useState<string>("10");

  const [fullName, setFullName] = useState("");
  const [cardNum, setCardNum] = useState("");
  const [expiry, setExpiry] = useState(""); // MM/YY or MM/YYYY
  const [cvv, setCvv] = useState("");
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [bundles, setBundles] = useState<boolean>(true);
  const [selectedPack, setSelectedPack] = useState<Pack | null>(packs[0]); // default 1st
  const [isB2binLoading, setIsB2binLoading] = useState(false);

  function handleCrypto() {
    if (isNaN(Number(amount))) {
      setMessage("Please enter amount!");
    } else if (parseInt(amount) < 10) {
      setMessage("You can not deposit less than $10.");
    } else {
      let req = {
        method: "POST",
        url: BASE_URL + "/api/create-crypto-charge",
        body: {
          name: "Awesome Product",
          description: "The best product ever!",
          pricing_type: "fixed_price",
          local_price: {
            amount: amount,
            currency: "USD",
          },
          amount: amount,
          user_id: user.userId,
        },
      };
      const newWin: Window | null = window.open("", "_blank");
      sendRequest(req, user.token, function (res: any) {
        if (res.resp == "error") {
          setMessage(res.message);
        } else if (res.resp == "success") {
          const hostedUrl = res.data.data.hosted_url;
          if (newWin) {
            newWin.location.href = hostedUrl;
          }
          setAmount("");
          setMessage("");
        }
      });
    }
    setTimeout(function () {
      setMessage("");
    }, 3500);
  }

  function handleCard() {
    if (isNaN(Number(amount))) {
      setMessage("Please enter amount!");
    } else if (parseInt(amount) < 10) {
      setMessage("You can not deposit less than $10.");
    } else {
      setSelected("stripe");
    }
  }

  useEffect(() => {
    setTimeout(function () {
      setMessage("");
    }, 4000);
  }, [message]);

  function __setAmount(v: any) {
    if (/^\d*$/.test(v)) {
      let m = parseInt(v);
      if (m >= 10 && m <= 9999) {
        setAmount(v);
      }
    }
  }

  const handleProceedWithCrypto = async () => {
    try {
      const res = await fetch("/api/deposit/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          amount: depositAmount,
        }),
      });

      const data = await res.json();

      if (!res.ok || !data.paymentPage) {
        alert(data?.message || "Unable to start crypto payment");
        return;
      }

      // ✅ Redirect to B2BINPAY hosted payment page
      window.location.href = data.paymentPage;
    } catch (err) {
      console.error(err);
      alert("Something went wrong. Please try again.");
    }
  };

  const PRICE_ID = "price_1T0f9q2NvbquX6Mq7hMxV3jB";

  async function handleStripeCheckout() {
    const res = await fetch("/api/stripe/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        priceId: PRICE_ID,
        quantity: 1,
        amount: depositAmount,
        currency: "USD",
      }),
    });

    const data = await res.json();

    if (data?.url) window.location.href = data.url;
    else alert(data?.error || "Checkout did not start. Please try again.");
  }

  const handleB2bin = async () => {
    setIsB2binLoading(true);
    try {
      const res = await fetch("/api/b2binpay/create-deposit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ walletId: "1", trackingId: "order_123" }),
      });
      console.log("res of b2bin", res);
      const { paymentPage } = await res.json();
      (console.log("paymentPage"), paymentPage);

      window.location.href = paymentPage;
      setIsB2binLoading(false);
    } catch (err: any) {
      console.error(err);
      setIsB2binLoading(false);

      alert("Something went wrong. Please try again.");
    }
  };

  const pay = async () => {
    setErr(null);

    // Basic validation (add more as needed)
    const cleanCard = cardNum.replace(/\s+/g, "");
    if (!cleanCard || cleanCard.length < 12)
      return setErr("Invalid card number");
    if (!cvv || cvv.length < 3) return setErr("Invalid CVV");
    if (!expiry) return setErr("Invalid expiry");

    // Parse expiry
    const m = expiry.trim().match(/^(\d{1,2})\s*\/\s*(\d{2}|\d{4})$/);
    if (!m) return setErr("Expiry must be MM/YY or MM/YYYY");

    const month = Number(m[1]);
    let year = Number(m[2]);
    if (month < 1 || month > 12) return setErr("Invalid expiry month");
    if (year < 100) year = 2000 + year; // 27 -> 2027

    setLoading(true);

    try {
      const res = await fetch("/api/paysafe/payment-handle", {
        method: "POST",
        headers: { "Conent-Type": "application/json" },
        body: JSON.stringify({
          amount: depositAmount, // cents
          currencyCode: "USD",
          fullName,
          card: {
            cardNum: cleanCard,
            cvv,
            cardExpiry: { month, year },
          },
          billingDetails: {
            country: "US",
            zip: "10001",
          },
        }),
      });

      const data = await res.json();
      if (!res.ok || data?.error) {
        setErr(data?.error?.message || "Payment handle failed");
        return;
      }

      if (res.ok) {
        setCardNum("");
        setCardNum("");
        setExpiry("");
        setCvv("");
      }

      const { paymentHandleToken } = data;

      // @ts-ignore
      paysafe?.checkout?.setup(
        paymentHandleToken,
        {
          environment: "TEST",
          merchantRefNum: "order_123",
          amount: 1000,
          currency: "USD",
        },
        (instance: any) => {
          instance.show();
        },
        (error: any) => {
          console.error("Paysafe error", error);
        },
      );
    } catch (e: any) {
      setErr(e?.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://hosted.paysafe.com/js/v1/latest/paysafe.min.js";
    script.async = true;
    document.body.appendChild(script);
  }, []);

  return (
    <div className="min-h-[calc(100vh-94px)] py-4 w-full flex items-center justify-center bg-[#0C0B11] overflow-hidden">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <div className="w-full max-w-184.75 mx-auto px-4 text-white text-center">
          {tab === "deposit" ? (
            <div className="fixed inset-0 z-99999 flex items-center justify-center bg-black/60 backdrop-blur-sm">
              <div className="relative w-full max-w-md px-4 md:px-0 md:max-w-197.5 ">
                {bundles ? (
                  <>
                    <div className="p-3 md:p-6 h-[400px] md:h-full overflow-y-auto bg-(--color-naviBlue) font-inter border border-[#29313D] space-y-3 2xl:space-y-4">
                      <div className="flex items-center gap-4">
                        <button
                          onClick={() => window.history.back()}
                          className="text-xs uppercase md:text-lg 2xl:text-2xl p-2 px-4 font-extrabold text-white bg-(--color-gray) hover:text-white italic font-sofia transition"
                        >
                          &lt; BACK
                        </button>
                        <h1 className="text-xs flex-1  text-left font-sofia uppercase md:text-lg 2xl:text-2xl font-extrabold text-white italic ">
                          Deposit Gems
                        </h1>
                      </div>
                      <GemsGrid
                        setBundles={setBundles}
                        onSelect={setSelectedPack}
                        setDepositAmount={setDepositAmount}
                      />
                    </div>
                  </>
                ) : (
                  <>
                    <div className="p-3 md:p-6 bg-(--color-naviBlue) font-inter border border-[#29313D] space-y-3 2xl:space-y-4">
                      <div className="flex items-center gap-4">
                        <button
                          onClick={() => setBundles(true)}
                          className="text-xs uppercase  md:text-lg 2xl:text-2xl p-2 px-4 font-extrabold text-white bg-(--color-gray) hover:text-white italic font-sofia transition"
                        >
                          &lt; BACK to bundles
                        </button>
                        <h1 className="text-xs font-sofia uppercase md:text-lg 2xl:text-2xl font-extrabold text-white italic ">
                          Deposit Details
                        </h1>
                      </div>
                      {selectedPack && (
                        <div className="relative w-full border border-[#29313D] bg-[#121924] px-8 py-2">
                          <div className="relative flex flex-col md:flex-row items-center justify-center gap-3 text-white">
                            <div className="flex items-center gap-2">
                              <img
                                src={selectedPack.img}
                                alt="diamond"
                                className=" w-8 md:h-10 md:w-10"
                              />
                              <span className="font-semibold text-xs md:text-base tracking-tight">
                                {selectedPack.gems} Gems
                              </span>
                            </div>

                            <div className="h-10 w-px hidden md:block bg-white/15" />

                            <div className="relative flex items-center gap-3">
                              <span className="relative font-semibold text-sm md:text-base tracking-tight text-[#FF348D]">
                                FREE
                              </span>

                              <div className="flex items-center gap-2">
                                <img
                                  src="/images/wallet/coin.svg"
                                  alt="coin"
                                  className="h-3 md:h-5"
                                />
                                <span className="font-semibold text-xs md:text-base tracking-tight">
                                  {selectedPack.wincoinsFree} WINCOINS
                                </span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}

                      <h1 className="font-semibold text-sm md:text-base 2xl:text-lg text-center">
                        Deposit amount
                      </h1>
                      <input
                        type="text"
                        inputMode="numeric"
                        className="w-full h-13.5 text-center bg-(--color-gray) rounded-md px-3 text-white outline-none
[appearance:textfield] 
[&::-webkit-outer-spin-button]:appearance-none 
[&::-webkit-inner-spin-button]:appearance-none"
                        value={depositAmount}
                        onChange={(e) => {
                          const v = e.target.value;
                          if (v === "" || /^\d*$/.test(v)) setDepositAmount(v); // only digits
                        }}
                      />

                      <h1 className="font-semibold text-sm md:text-lg text-center">
                        Choose payment option
                      </h1>
                      {/* onClick={() => handleCard() */}
                      {/* onClick={() => setTab("withdraw")} */}
                      <div
                        onClick={handleStripeCheckout}
                        className="border cursor-pointer border-(--color-gray) font-medium text-xs md:text-sm flex items-center gap-4 justify-center w-full py-3"
                      >
                        <img src="/images/wallet/visa.svg" alt="visa" />
                        <span>Proceed with Stripe</span>
                      </div>

                      <div
                        onClick={() => handleCrypto()}
                        className="border cursor-pointer border-(--color-gray) font-medium text-xs md:text-sm flex items-center gap-4 justify-center w-full py-3"
                      >
                        <img src="/images/wallet/p.svg" alt="paypal" />
                        <span>Proceed with PayPal</span>
                      </div>

                      <div
                        // onClick={() => handleProceedWithCrypto()}
                        onClick={() => {
                          handleB2bin();
                        }}
                        className="border cursor-pointer border-(--color-gray) font-medium text-xs md:text-sm flex items-center gap-4 justify-center w-full py-3"
                      >
                        <img src="/images/wallet/badge.svg" alt="badge" />
                        <span>
                          {isB2binLoading
                            ? "wait please..."
                            : "Proceed with b2bin crypto "}{" "}
                        </span>
                      </div>

                      <button className="bg-(--color-blue) hover:bg-(--color-hoverBlue) duration-300 font-medium text-xs md:text-base font-onest flex items-center justify-center w-full py-3">
                        Continue
                      </button>
                    </div>
                    {selected == "stripe" ? (
                      <PaymentForm
                        amount={parseFloat(amount) * 100}
                        setSelected={setSelected}
                      />
                    ) : null}
                  </>
                )}
              </div>
            </div>
          ) : (
            <div className="fixed inset-0 z-99999 flex items-center justify-center flex-col bg-black/60 backdrop-blur-sm">
              <div className="p-3 md:p-0">
                <div className="flex items-center justify-center flex-col md:flex-row gap-4 mb-6 xl:mb-0 h-16">
                  <div className="flex font-bold font-sofia text-xs mb-4 text-white md:text-lg 2xl:text-2xl gap-3 items-center">
                    <button
                      onClick={() => setTab("deposit")}
                      className={`${
                        tab === "deposit"
                          ? "bg-(--color-blue)"
                          : "bg-(--color-naviBlue)"
                      } px-3 md:px-7 2xl:px-9 py-1.5 hover:bg-(--color-blue) duration-300 md:py-2.5 cursor-pointer`}
                    >
                      DEPOSIT
                    </button>
                    <Link
                      href="/withdraw"
                      className={`${
                        tab === "withdraw"
                          ? "bg-(--color-naviBlue)"
                          : "bg-(--color-naviBlue)"
                      } px-3 md:px-7 2xl:px-9 py-1.5 hover:bg-(--color-blue) duration-300 md:py-2.5 cursor-pointer`}
                    >
                      WITHDRAW
                    </Link>
                  </div>
                </div>
                <div className="p-3 md:py-4 md:px-27.5 bg-(--color-naviBlue) rounded-xl space-y-1">
                  <p className="text-sm font-sofia flex items-center gap-6 justify-center md:text-xl font-semibold  leading-relaxed">
                    <span>&lt; </span>
                    <span>CARD PAYMENT</span>
                  </p>

                  <h1 className="font-semibold font-inter text-sm md:text-lg text-center">
                    Deposit amount
                  </h1>
                  <div className="flex justify-center">
                    <h1 className="border font-inter border-(--color-gray) w-fit px-3 md:px-6 mt-1 py-2 font-semibold text-sm md:text-lg text-center">
                      ${depositAmount === "" ? 0 : depositAmount}
                    </h1>
                  </div>

                  <div className="w-full font-inter max-w-md mx-auto text-white space-y-5">
                    {/* Full Name */}
                    <div>
                      <label className="block text-sm text-left font-medium mb-1">
                        Full Name
                      </label>
                      <input
                        value={fullName}
                        onChange={(e) => setFullName(e.target.value)}
                        type="text"
                        className="w-full bg-(--color-gray) h-8 md:h-12 rounded-sm px-3 focus:outline-none"
                      />
                    </div>

                    {/* Card Number */}
                    <div>
                      <label className="block text-left text-sm font-medium mb-1">
                        Card Number
                      </label>
                      <input
                        value={cardNum}
                        onChange={(e) => setCardNum(e.target.value)}
                        inputMode="numeric"
                        autoComplete="cc-number"
                        className="w-full bg-(--color-gray) h-8 md:h-12 rounded-sm px-3 focus:outline-none"
                      />
                    </div>

                    {/* Expiry Date + CVV or Expiry */}
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-left text-sm font-medium mb-1">
                          Expiry Date
                        </label>
                        <input
                          value={expiry}
                          onChange={(e) => setExpiry(e.target.value)}
                          placeholder="MM/YY"
                          inputMode="numeric"
                          autoComplete="cc-exp"
                          className="w-full bg-(--color-gray) h-8 md:h-12 rounded-sm px-3 focus:outline-none"
                        />
                      </div>

                      <div>
                        <label className="block text-left text-sm font-medium mb-1">
                          CVV
                        </label>
                        <input
                          value={cvv}
                          onChange={(e) => setCvv(e.target.value)}
                          placeholder="123"
                          inputMode="numeric"
                          autoComplete="cc-csc"
                          className="w-full bg-(--color-gray) h-8 md:h-12 rounded-sm px-3 focus:outline-none"
                        />
                      </div>
                    </div>
                    {err && <p className="text-red-400 text-sm">{err}</p>}
                  </div>
                  <button
                    onClick={pay}
                    className="bg-(--color-blue) mt-3 hover:bg-(--color-hoverBlue) duration-300 font-medium text-xs md:text-base font-onest flex items-center justify-center w-full py-3"
                  >
                    {loading ? "Processing..." : "Continue"}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default Page;
