// src/Pages/manager/ManagerSettingsPage.jsx
import React, { useContext, useState } from "react";
import { useStripe, useElements, CardElement } from "@stripe/react-stripe-js";
import { GlobalContext, showToast } from "Src/globalContext";
import MkdSDK from "Utils/MkdSDK";

const ManagerSettingsPage = () => {
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  const stripe = useStripe();
  const elements = useElements();
  const [email, setEmail] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [phone, setPhone] = useState("");
  const [paymentError, setPaymentError] = useState(null);

  const handleAddMember = async () => {
    if (!stripe || !elements) {
      setPaymentError("Stripe has not been initialized");
      return;
    }

    const cardElement = elements.getElement(CardElement);
    if (!cardElement) {
      setPaymentError("Card element not found");
      return;
    }

    try {
      const sdk = new MkdSDK();
      const paymentIntentResponse = await sdk.callRawAPI(
        "/v3/api/custom/equality_record/subscription/member/payment",
        { email, firstName, lastName, phone },
        "POST"
      );

      if (paymentIntentResponse.error) {
        throw new Error(paymentIntentResponse.message);
      }

      const { client_secret } = paymentIntentResponse;

      const { error, paymentIntent } = await stripe.confirmCardPayment(
        client_secret,
        {
          payment_method: {
            card: cardElement,
            billing_details: {
              email,
              name: `${firstName} ${lastName}`,
              phone,
            },
          },
        }
      );

      if (error) {
        setPaymentError(error.message);
        return;
      }

      const confirmResponse = await sdk.callRawAPI(
        "/v3/api/custom/equality_record/subscription/member/payment/confirm",
        { paymentIntentId: paymentIntent.id },
        "POST"
      );

      if (confirmResponse.error) {
        throw new Error(confirmResponse.message);
      }

      showToast(globalDispatch, "Member added successfully", 4000);
    } catch (error) {
      console.error("Error adding member:", error);
      showToast(
        globalDispatch,
        error.message || "Failed to add member",
        4000,
        "error"
      );
    }
  };

  return (
    <div className="p-6">
      <h2 className="mb-6 text-2xl font-semibold text-white">Add Member</h2>
      <form className="space-y-4">
        <div>
          <label className="block text-white">Email</label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full rounded border border-stroke bg-transparent px-4 py-2 text-white"
            placeholder="Enter email"
          />
        </div>
        <div>
          <label className="block text-white">First Name</label>
          <input
            type="text"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
            className="w-full rounded border border-stroke bg-transparent px-4 py-2 text-white"
            placeholder="Enter first name"
          />
        </div>
        <div>
          <label className="block text-white">Last Name</label>
          <input
            type="text"
            value={lastName}
            onChange={(e) => setLastName(e.target.value)}
            className="w-full rounded border border-stroke bg-transparent px-4 py-2 text-white"
            placeholder="Enter last name"
          />
        </div>
        <div>
          <label className="block text-white">Phone</label>
          <input
            type="tel"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            className="w-full rounded border border-stroke bg-transparent px-4 py-2 text-white"
            placeholder="Enter phone number"
          />
        </div>
        <div>
          <label className="block text-white">Card Details</label>
          <CardElement
            options={{
              style: {
                base: {
                  fontSize: "16px",
                  color: "#ffffff",
                  "::placeholder": {
                    color: "#aab7c4",
                  },
                },
                invalid: {
                  color: "#dc3545",
                },
              },
            }}
          />
          {paymentError && (
            <p className="mt-2 text-sm text-danger">{paymentError}</p>
          )}
        </div>
        <button
          type="button"
          onClick={handleAddMember}
          className="rounded-md bg-primary px-6 py-2 text-white hover:bg-opacity-90"
        >
          Add Member
        </button>
      </form>
    </div>
  );
};

export default ManagerSettingsPage;
