import React from 'react';
import type { TFunction } from 'i18next';
import { createTenantPaddleCheckout } from '../../api';

type PaddleCheckoutProps = {
  packageId: number;
  onSuccess: () => void;
  t: TFunction;
};

export function PaddleCheckout({ packageId, onSuccess, t }: PaddleCheckoutProps) {
  const [error, setError] = React.useState<string | null>(null);
  const [busy, setBusy] = React.useState(false);

  const handleClick = async () => {
    if (busy) return;
    setBusy(true);
    setError(null);

    try {
      const checkout = await createTenantPaddleCheckout(packageId);
      if (checkout?.checkout_url) {
        window.open(checkout.checkout_url, '_blank', 'noopener');
      }
      onSuccess();
    } catch (err) {
      const message = err instanceof Error ? err.message : t('errors.generic', 'Fehler');
      setError(message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="flex flex-col gap-2">
      {error ? (
        <div role="alert" className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800">
          {error}
        </div>
      ) : null}
      <button
        type="button"
        onClick={handleClick}
        disabled={busy}
        className="inline-flex items-center justify-center rounded-md bg-slate-900 px-4 py-2 text-white disabled:opacity-70"
      >
        {busy ? t('welcome.packages.loading', 'Lädt…') : t('welcome.packages.purchase', 'Jetzt kaufen')}
      </button>
    </div>
  );
}

export default function WelcomeOrderSummaryPage() {
  return (
    <div className="p-6">
      <p>Order summary placeholder</p>
    </div>
  );
}

