"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/lib/auth-context";

interface StripePaymentButtonProps {
  tier: "basic" | "pro" | "enterprise";
  amount: number;
  storageLimit: number;
}

export function StripePaymentButton({
  tier,
  amount,
  storageLimit,
}: StripePaymentButtonProps) {
  const [loading, setLoading] = useState(false);
  const { user } = useAuth();
  const router = useRouter();

  const handlePayment = async () => {
    if (!user) {
      // Redirect to login page
      router.push("/login?redirect=/pricing");
      return;
    }

    setLoading(true);

    try {
      const response = await fetch("/api/create-checkout-session", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          tier,
          userId: user.id,
        }),
      });

      // Check if response is JSON before parsing
      const contentType = response.headers.get("content-type");
      if (!contentType || !contentType.includes("application/json")) {
        throw new Error(
          "Invalid response from server. Please check your Stripe configuration."
        );
      }

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to create checkout session");
      }

      // Redirect to Stripe Checkout
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (error) {
      console.error("Payment error:", error);
      alert("Failed to start payment process. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button
      onClick={handlePayment}
      disabled={loading}
      className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium px-6 py-3 rounded-md transition-colors"
    >
      {loading ? "Processing..." : `Subscribe - $${amount}/month`}
    </Button>
  );
}
