"use client";

import { useState } from "react";
import { PaymentStep } from "../../../../checkout/components/PaymentStep";

// Shown only for a still-unpaid Überweisung order (see page.tsx's own
// eligibility check, mirroring api/account/orders/[orderNumber]/
// switch-to-stripe/route.ts's authoritative one) — lets a customer switch
// to Kreditkarte/PayPal instead of waiting on their own bank transfer.
// Reuses PaymentStep (the exact same Stripe collection UI checkout uses)
// once this endpoint hands back a clientSecret — the order already
// exists, this only changes how it gets paid.
export function SwitchPaymentButton({ orderNumber }: { orderNumber: string }) {
  const [state, setState] = useState<
    | { step: "idle" }
    | { step: "loading" }
    | { step: "error"; reason: string }
    | { step: "paying"; clientSecret: string; orderId: number; testMode: boolean; providerReference?: string }
  >({ step: "idle" });

  async function start() {
    setState({ step: "loading" });
    try {
      const res = await fetch(`/api/account/orders/${encodeURIComponent(orderNumber)}/switch-to-stripe`, {
        method: "POST",
      });
      const data = await res.json();
      if (!data.ok) {
        setState({ step: "error", reason: data.reason || "Umstellung fehlgeschlagen." });
        return;
      }
      setState({
        step: "paying",
        clientSecret: data.clientSecret,
        orderId: data.orderId,
        testMode: Boolean(data.testMode),
        providerReference: data.providerReference,
      });
    } catch {
      setState({ step: "error", reason: "Umstellung gerade nicht möglich." });
    }
  }

  if (state.step === "paying") {
    return (
      <div className="flex flex-col gap-4 w-full border border-border rounded-md p-5">
        <p className="font-semibold text-body-sm text-text-primary">Mit Kreditkarte/PayPal bezahlen</p>
        <PaymentStep
          clientSecret={state.clientSecret}
          orderNumber={orderNumber}
          orderId={state.orderId}
          testMode={state.testMode}
          providerReference={state.providerReference}
          returnContext="account"
        />
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-2 items-start">
      <button
        type="button"
        onClick={start}
        disabled={state.step === "loading"}
        className={`px-5 py-3 rounded-sm border border-border hover:border-brand font-bold text-body-sm text-text-primary transition-colors ${state.step === "loading" ? "opacity-70 pointer-events-none" : ""}`}
      >
        {state.step === "loading" ? "…" : "Zahlungsart ändern"}
      </button>
      {state.step === "error" && <p className="text-label text-red-600">{state.reason}</p>}
    </div>
  );
}
