"use client";

import { useState } from "react";
import { X, CreditCard, Loader } from "lucide-react";
import { useRazorpay } from "react-razorpay";
import toast from "react-hot-toast";
import api from "@/app/api/api";

interface PaymentModalProps {
  isOpen: boolean;
  onClose: () => void;
  plan: {
    id: string;
    name: string;
    price: string;
    period: string;
  };
  onSuccess: () => void;
}

export const PaymentModal = ({
  isOpen,
  onClose,
  plan,
  onSuccess,
}: PaymentModalProps) => {
  const [loading, setLoading] = useState(false);
  const { Razorpay } = useRazorpay();

  if (!isOpen) return null;

  const handlePayment = async () => {
    if (!Razorpay) {
      toast.error("Payment system not loaded. Please refresh and try again.");
      return;
    }

    setLoading(true);

    try {
      // Extract numeric value from price (e.g., "$49" -> 49)
      const amount = parseFloat(plan.price.replace("$", ""));

      // Create order on backend
      const orderResponse = await api.post("/payment/create-order", {
        amount,
        currency: "INR",
        planName: plan.name,
      });

      const { orderId, key } = orderResponse.data;

      const options = {
        key,
        amount: amount * 100, // convert to paise
        currency: "INR",
        name: "ImageOptimizer",
        description: `${plan.name} Plan Subscription`,
        order_id: orderId,
        handler: async (response: any) => {
          try {
            const verifyResponse = await api.post("/payment/verify-payment", {
              razorpay_order_id: response.razorpay_order_id,
              razorpay_payment_id: response.razorpay_payment_id,
              razorpay_signature: response.razorpay_signature,
              planName: plan.name,
            });

            if (verifyResponse.data.success) {
              toast.success("Payment successful! Subscription active.");
              onSuccess();
            } else {
              toast.error("Payment verification failed");
            }
          } catch (error) {
            console.error("Payment verification error:", error);
            toast.error("Payment verification failed");
          }
        },
        prefill: {
          name: "Customer Name",
          email: "customer@example.com",
        },
        theme: {
          color: "#3B82F6",
        },
        modal: {
          ondismiss: () => setLoading(false),
        },
      };

      const razorpayInstance = new Razorpay(options as any);
      razorpayInstance.open();
    } catch (error: any) {
      console.error("Payment initiation error:", error);
      toast.error(error.response?.data?.error || "Failed to initiate payment");
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-2xl p-8 max-w-md w-full mx-4">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-2xl font-bold text-gray-900">Complete Payment</h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="mb-6">
          <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-4 mb-4">
            <h3 className="font-semibold text-gray-900">{plan.name} Plan</h3>
            <p className="text-2xl font-bold text-blue-600">
              {plan.price}
              <span className="text-sm text-gray-600">{plan.period}</span>
            </p>
          </div>

          <div className="space-y-2 text-sm text-gray-600">
            <p>• Secure payment powered by Razorpay</p>
            <p>• Instant activation after payment</p>
            <p>• Cancel anytime</p>
          </div>
        </div>

        <button
          onClick={handlePayment}
          disabled={loading}
          className="w-full flex items-center justify-center space-x-2 px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-600 text-white font-semibold rounded-lg hover:from-blue-600 hover:to-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
        >
          {loading ? (
            <>
              <Loader className="w-5 h-5 animate-spin" />
              <span>Processing...</span>
            </>
          ) : (
            <>
              <CreditCard className="w-5 h-5" />
              <span>Pay {plan.price}</span>
            </>
          )}
        </button>

        <p className="text-xs text-gray-500 text-center mt-4">
          By proceeding, you agree to our Terms of Service and Privacy Policy
        </p>
      </div>
    </div>
  );
};
