"use client";

import { useState } from "react";
import { loadStripe } from "@stripe/stripe-js";
import { BASE_URL } from "@/constants";
import { useSelector } from "react-redux";
import {User} from "@/constants/types";
import {
  Elements,
  CardElement,
  useStripe,
  useElements,
} from "@stripe/react-stripe-js";

const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);

async function saveStripe(amount, paymentIntent, user) {
  try {
    // const token = localStorage.getItem("auth_token");
    const res = await fetch(BASE_URL + "/api/save-stripe", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${user.token}`,
      },
      body: JSON.stringify({
        user_id: localStorage.getItem("otp_user_id"),
        paymentIntent: paymentIntent,
        amount: amount,
      }),
    });

    const data = await res.json();
    if (data.resp === "success") {
      const bal = data.balance;
      localStorage.setItem("otp_user_balance", bal);
      document.getElementById("u_balance").innerText = bal;
    }
    return data;
  } catch (err) {
    console.error("Error:", err);
  }
}

function CheckoutForm({ amount, setSelected , user}) {
  const stripe = useStripe();
  const elements = useElements();
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [fullname, setFullName] = useState("");
  const [address, setAddress] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!stripe || !elements) return;
    setLoading(true);

    // 1️⃣ Create a PaymentIntent from backend
    const res = await fetch(`${BASE_URL}/api/payment-intent`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        amount: parseFloat(amount), // e.g. 10.50
        fullname,
        address,
      }),
    });

    const { clientSecret, error } = await res.json();
    if (error) {
      setMessage(error);
      setLoading(false);
      return;
    }

    // 2️⃣ Confirm payment with Stripe
    const { error: stripeError, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
      payment_method: {
        card: elements.getElement(CardElement),
      },
    });

    if (stripeError) {
      setMessage(stripeError.message);
    } else if (paymentIntent.status === "succeeded") {
      const resp = await saveStripe(amount, paymentIntent, user);
      setMessage(resp.msg || "Payment successful!");
      setSelected("");
    }

    setTimeout(() => setMessage(""), 7000);
    setLoading(false);
  };

  const cardOptions = {
    style: {
      base: {
        color: "#000",
        fontSize: "16px",
        "::placeholder": { color: "#888" },
      },
      invalid: { color: "#e5424d" },
    },
    hidePostalCode: true,
  };

  return (
    <form onSubmit={handleSubmit} className="text-black my-5 max-w-md mx-auto p-4 bg-white rounded-xl shadow">
      <h2 className="text-xl font-bold mb-4">Pay with Card</h2>

      {message && <p className="mt-3 text-center text-green-600">{message}</p>}

      <label className="text-left block mt-3">Full Name</label>
      <input
        type="text"
        placeholder="Enter your full name"
        value={fullname}
        onChange={(e) => setFullName(e.target.value)}
        required
        className="w-full h-10 border border-gray-400 rounded px-3 mb-4"
      />

      <label className="text-left block mt-3">Card Info</label>
      <div className="p-3 border rounded mb-4">
        <CardElement options={cardOptions} />
      </div>

      <label className="text-left block mt-3">Address</label>
      <input
        type="text"
        placeholder="Enter your full address"
        value={address}
        onChange={(e) => setAddress(e.target.value)}
        required
        className="w-full h-10 border border-gray-400 rounded px-3 mb-4"
      />

      <button
        type="submit"
        disabled={!stripe || loading}
        className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700"
      >
        {loading ? "Processing..." : `Pay $${amount/100}`}
      </button>
    </form>
  );
}


export default function PaymentForm({ amount, setSelected }) {
  const options = {
    appearance: { theme: "night" }, // ✅ only appearance here
  };
  const user = useSelector(state => state.auth.user);
  return (
    <Elements stripe={stripePromise} options={options}>
      <CheckoutForm user={user} amount={amount} setSelected={setSelected} />
    </Elements>
  );
}
