import { useState, useRef } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { verifyCheckoutSession } from "../../api/stripe";
import { useAuth } from "../../contexts/AuthContext";
import "./Subscribe.css";

export default function CheckoutReturn() {
  const { sessionId } = useParams();
  const navigate = useNavigate();
  const { refreshAccount } = useAuth();
  const [error, setError] = useState(null);
  const started = useRef(false);

  if (sessionId && !started.current) {
    started.current = true;
    verifyCheckoutSession(sessionId)
      .then(() => refreshAccount())
      .then(() => navigate("/addresses", { replace: true }))
      .catch((err) => setError(err.message || "Payment verification failed"));
  }

  if (!sessionId) {
    return (
      <div className="subscribe">
        <div className="subscribe__container">
          <h1 className="subscribe__title">Koin Ping</h1>
          <div className="alert alert--error">No session ID found.</div>
          <p><a href="/subscribe">Back to Subscribe</a></p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="subscribe">
        <div className="subscribe__container">
          <h1 className="subscribe__title">Koin Ping</h1>
          <div className="alert alert--error">{error}</div>
          <p><a href="/subscribe">Try again</a></p>
        </div>
      </div>
    );
  }

  return (
    <div className="subscribe">
      <div className="subscribe__container">
        <h1 className="subscribe__title">Koin Ping</h1>
        <p>Verifying your payment...</p>
      </div>
    </div>
  );
}
