"use client";

import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
import { useState } from "react";
import { AlertCircle } from "lucide-react";
const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH || "";
interface PayPalCheckoutProps {
  clientId: string;
  amount: number;
  currency?: string;
  itemName?: string;
  quantity?: number;
  onSuccess: (captureId: string) => void;
  onError: (msg: string) => void;
}

export function PayPalCheckout({
  clientId,
  amount,
  currency = "USD",
  itemName,
  quantity = 1,
  onSuccess,
  onError,
}: PayPalCheckoutProps) {
  const [sdkError, setSdkError] = useState("");

  if (!clientId) {
    return (
      <div
        className="flex items-center gap-2 py-3 px-4 rounded-xl text-[12px]"
        style={{
          background: "rgba(244,63,94,0.08)",
          color: "#f43f5e",
          border: "1px solid rgba(244,63,94,0.15)",
        }}
      >
        <AlertCircle size={14} strokeWidth={1.8} />
        PayPal Client ID not configured. Add it in payment settings.
      </div>
    );
  }

  return (
    <PayPalScriptProvider
      options={{
        clientId,
        currency,
        intent: "capture",
        components: "buttons",
        // sandbox / live is controlled by the clientId itself
      }}
      deferLoading={false}
    >
      {sdkError ? (
        <div
          className="flex items-center gap-2 py-3 px-4 rounded-xl text-[12px]"
          style={{
            background: "rgba(244,63,94,0.08)",
            color: "#f43f5e",
            border: "1px solid rgba(244,63,94,0.15)",
          }}
        >
          <AlertCircle size={14} strokeWidth={1.8} />
          {sdkError}
        </div>
      ) : (
        <div className="paypal-btn-wrapper">
          <PayPalButtons
            style={{
              layout: "vertical",
              color: "blue",
              shape: "rect",
              label: "pay",
              height: 45,
            }}
            fundingSource={undefined}
            createOrder={async () => {
              const res = await fetch(`${BASE_PATH}/api/paypal/create-order`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ amount, currency, itemName, quantity }),
              });
              const data = await res.json();
              if (!res.ok || !data.orderId) {
                throw new Error(data.error ?? "Failed to create PayPal order");
              }
              return data.orderId as string;
            }}
            onApprove={async (data) => {
              const res = await fetch(`${BASE_PATH}/api/paypal/capture-order`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ orderId: data.orderID }),
              });
              const capture = await res.json();
              if (!res.ok || !capture.success) {
                onError(capture.error ?? "Payment capture failed");
                return;
              }
              onSuccess(capture.captureId as string);
            }}
            onError={(err) => {
              const msg =
                err instanceof Error ? err.message : "PayPal error occurred";
              setSdkError(msg);
              onError(msg);
            }}
            onCancel={() => onError("Payment cancelled")}
          />
        </div>
      )}
    </PayPalScriptProvider>
  );
}
