import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

interface CoinbaseCheckoutOptions {
  type: "subscription" | "credits" | "invoice";
  planId?: string;
  billingCycle?: "monthly" | "yearly";
  creditPackId?: string;
  invoiceId?: string;
}

export const useCoinbaseCheckout = () => {
  const [loading, setLoading] = useState(false);

  const initiateCoinbaseCheckout = async (options: CoinbaseCheckoutOptions) => {
    setLoading(true);
    try {
      const successUrl = `${window.location.origin}/subscription?payment=success&method=crypto`;
      const cancelUrl = `${window.location.origin}/subscription?payment=cancelled`;

      const { data, error } = await supabase.functions.invoke("coinbase-checkout", {
        body: {
          type: options.type,
          plan_id: options.planId,
          billing_cycle: options.billingCycle,
          credit_pack_id: options.creditPackId,
          invoice_id: options.invoiceId,
          success_url: successUrl,
          cancel_url: cancelUrl,
        },
      });

      if (error) {
        const msg = error.message || "";
        if (msg.includes("not configured") || msg.includes("not enabled")) {
          toast.error("Cryptocurrency payments are not available yet. The admin needs to configure Coinbase Commerce credentials in the admin panel.");
        } else {
          toast.error(msg || "Failed to initiate crypto checkout");
        }
        setLoading(false);
        return;
      }

      if (data?.error) {
        const msg = data.error || "";
        if (msg.includes("not configured") || msg.includes("not enabled")) {
          toast.error("Cryptocurrency payments are not available yet. The admin needs to configure Coinbase Commerce credentials in the admin panel.");
        } else {
          toast.error(msg || "Failed to initiate crypto checkout");
        }
        setLoading(false);
        return;
      }

      if (data?.hostedUrl) {
        window.location.href = data.hostedUrl;
      } else {
        toast.error("No checkout URL received from Coinbase Commerce");
        setLoading(false);
      }
    } catch (error) {
      console.error("Coinbase checkout error:", error);
      const msg = error instanceof Error ? error.message : "";
      if (msg.includes("not configured") || msg.includes("not enabled")) {
        toast.error("Cryptocurrency payments are not available yet. The admin needs to configure Coinbase Commerce credentials in the admin panel.");
      } else {
        toast.error(msg || "Failed to start crypto checkout");
      }
      setLoading(false);
    }
  };

  return {
    initiateCoinbaseCheckout,
    loading,
  };
};
