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

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

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

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

      const { data, error } = await supabase.functions.invoke("paypal-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") || msg.includes("Authentication failed")) {
          toast.error("PayPal payments are not available yet. The admin needs to configure valid PayPal credentials in the admin panel.");
        } else {
          toast.error(msg || "Failed to initiate PayPal checkout");
        }
        setLoading(false);
        return;
      }

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

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

  return {
    initiatePayPalCheckout,
    loading,
  };
};
