import React, { useState, useEffect } from "react";
import { PayPalButtons, PayPalScriptProvider } from "@paypal/react-paypal-js";
import axios from "axios";
import { useRazorpay } from "react-razorpay";
import { useCurrency } from "@/app/contexts/currencyContext";

const PaymentComponent = ({ amount, onSuccess }) => {
  const { error: razorpayError, isLoading, Razorpay } = useRazorpay();
  const [error, setError] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [showPopup, setShowPopup] = useState(false);
  const [shippingData, setShippingData] = useState({
    address_line_1: "",
    address_line_2: "",
    state: "",
    city: "",
    country_code: "",
    postal_code: "",
    phone_number: "", 
  });
  const [shippingInfoCollected, setShippingInfoCollected] = useState(false);
  
  const { selectedCurrency, convertPrice, exchangeRates } = useCurrency();
  const amountInSelectedCurrency = convertPrice(amount);
  const [usdAmount, setUsdAmount] = useState(null);
  
  useEffect(() => {
    const calculateUsdAmount = async () => {
      try {
        if (selectedCurrency === 'USD') {
          setUsdAmount(amountInSelectedCurrency);
          return;
        }
        
        if (exchangeRates && exchangeRates['USD']) {
          const usdRate = exchangeRates['USD'];
          setUsdAmount((amountInSelectedCurrency / usdRate).toFixed(2));
          return;
        }
        
        const response = await axios.get('https://api.exchangerate-api.com/v4/latest/' + selectedCurrency);
        if (response.data && response.data.rates && response.data.rates.USD) {
          const usdRate = response.data.rates.USD;
          setUsdAmount((amountInSelectedCurrency * usdRate).toFixed(2));
        } else {
          throw new Error("Failed to fetch USD exchange rate");
        }
      } catch (err) {
        console.error("Error calculating USD amount:", err);
        if (selectedCurrency === 'INR') {
          setUsdAmount((amountInSelectedCurrency / 75).toFixed(2));
        } else {
          setUsdAmount(amountInSelectedCurrency);
        }
      }
    };

    calculateUsdAmount();
  }, [amountInSelectedCurrency, selectedCurrency, exchangeRates]);

  const createOrder = async () => {
    try {
      const response = await axios.post("/api/razorpay/order", {
        amount: amount * 100, // Amount in paise
        currency: "INR",
      });
      return response.data;
    } catch (error) {
      console.error("Error creating order:", error);
      throw error;
    }
  };

  const handlePaymentSuccess = (response) => {
    onSuccess?.({
      ...response,
      address: shippingData, // Include the shipping data in the success callback
    });
  };

  const handleRazorpayPayment = async () => {
    try {
      const order = await createOrder();
      
      const options = {
        key: "rzp_live_REdeGZclfm8KFo",
        amount: order.amount,
        currency: order.currency,
        name: "Rudraksha",
        description: "",
        order_id: order.id,
        prefill: {
          name: shippingData.address_line_1,
          email: shippingData.address_line_2,
          contact: shippingData.phone_number || shippingData.city,
        },
        handler: (response) => {
          response.address = shippingData;
          handlePaymentSuccess(response);
        },
      };

      const razorpayInstance = new Razorpay(options);
      razorpayInstance.open();
    } catch (error) {
      setError("Payment failed. Please try again.");
      console.error("Razorpay error:", error);
    }
  };

  const handlePopupSubmit = () => {
    if (!shippingData.address_line_1 || !shippingData.city || !shippingData.postal_code || !shippingData.phone_number) {
      setError("Please fill in all required fields.");
      return;
    }
    
    // Validate phone number
    const phoneRegex = /^\+?[0-9]{10,15}$/;
    if (!phoneRegex.test(shippingData.phone_number)) {
      setError("Please enter a valid phone number (10-15 digits).");
      return;
    }
    
    setShowPopup(false);
    setShippingInfoCollected(true);
    setError(null);
  };

  return (
    <div className="max-w-md mx-auto">
      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          {error}
        </div>
      )}
      {razorpayError && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          Error loading Razorpay: {razorpayError}
        </div>
      )}
      
      {shippingInfoCollected && (
        <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
          Shipping information collected ✓
          <button 
            onClick={() => setShowPopup(true)}
            className="ml-2 text-sm underline"
          >
            Edit
          </button>
        </div>
      )}

      {!shippingInfoCollected && (
        <button
          onClick={() => setShowPopup(true)}
          className="w-full bg-gray-200 text-gray-800 py-2 px-4 rounded hover:bg-gray-300 mb-4"
        >
          Enter Shipping Information
        </button>
      )}

      {/* Payment options - only enabled after shipping info is collected */}
      <div className={!shippingInfoCollected ? "opacity-50 pointer-events-none" : ""}>
        <PayPalScriptProvider
          options={{
            "client-id": process.env.NEXT_PUBLIC_CLIENT_ID,
            currency: "USD", // PayPal requires USD or other supported currencies
          }}
        >
          {usdAmount && (
            <PayPalButtons
              style={{
                layout: "horizontal",
                label: "checkout",
                tagline: false,
                fundingicons: true,
              }}
              disabled={isProcessing || !shippingInfoCollected}
              className="w-full"
              createOrder={(data, actions) => {
                return actions.order.create({
                  purchase_units: [
                    {
                      amount: {
                        value: usdAmount,
                        currency_code: "USD",
                      },
                    },
                  ],
                  application_context: {
                    shipping_preference: "GET_FROM_FILE",
                  },
                });
              }}
              onApprove={async (data, actions) => {
                try {
                  setIsProcessing(true);
                  const order = await actions.order.capture();
                  order.address = shippingData; // Add shipping data to PayPal order
                  handlePaymentSuccess(order);
                } catch (err) {
                  setError("Payment failed. Please try again.");
                  console.error("Payment error:", err);
                } finally {
                  setIsProcessing(false);
                }
              }}
              onError={(err) => {
                setError("Payment failed. Please try again.");
                console.error("PayPal error:", err);
              }}
            />
          )}
        </PayPalScriptProvider>

        <button
          onClick={handleRazorpayPayment}
          disabled={isProcessing || isLoading || !shippingInfoCollected}
          className="mt-4 w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"
        >
          {isLoading ? "Loading Razorpay..." : "Pay with Razorpay"}
        </button>
      </div>

      {showPopup && (
        <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50" style={{ zIndex: 1000 }}>
          <div className="bg-white p-6 rounded-lg shadow-lg w-96">
            <h3 className="text-lg font-medium mb-4">Enter Your Shipping Details</h3>
            <input
              type="text"
              placeholder="Address Line 1 *"
              value={shippingData.address_line_1}
              onChange={(e) => setShippingData({ ...shippingData, address_line_1: e.target.value })}
              className="w-full p-2 mb-4 border border-gray-300 rounded"
            />
            <input
              type="text"
              placeholder="Address Line 2"
              value={shippingData.address_line_2}
              onChange={(e) => setShippingData({ ...shippingData, address_line_2: e.target.value })}
              className="w-full p-2 mb-4 border border-gray-300 rounded"
            />
            <input
              type="text"
              placeholder="City *"
              value={shippingData.city}
              onChange={(e) => setShippingData({ ...shippingData, city: e.target.value })}
              className="w-full p-2 mb-4 border border-gray-300 rounded"
            />
            <input
              type="text"
              placeholder="State"
              value={shippingData.state}
              onChange={(e) => setShippingData({ ...shippingData, state: e.target.value })}
              className="w-full p-2 mb-4 border border-gray-300 rounded"
            />
            <input
              type="text"
              placeholder="Country Code *"
              value={shippingData.country_code}
              onChange={(e) => setShippingData({ ...shippingData, country_code: e.target.value })}
              className="w-full p-2 mb-4 border border-gray-300 rounded"
            />
            <input
              type="text"
              placeholder="Postal Code *"
              value={shippingData.postal_code}
              onChange={(e) => setShippingData({ ...shippingData, postal_code: e.target.value })}
              className="w-full p-2 mb-4 border border-gray-300 rounded"
            />
            <input
              type="tel"
              placeholder="Phone Number *"
              value={shippingData.phone_number}
              onChange={(e) => setShippingData({ ...shippingData, phone_number: e.target.value })}
              className="w-full p-2 mb-4 border border-gray-300 rounded"
            />
            <div className="flex gap-2">
              <button
                onClick={() => setShowPopup(false)}
                className="w-1/2 bg-gray-300 text-gray-800 py-2 px-4 rounded hover:bg-gray-400"
              >
                Cancel
              </button>
              <button
                onClick={handlePopupSubmit}
                className="w-1/2 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"
              >
                Save Address
              </button>
            </div>
          </div>
        </div>
      )}

      <p className="mt-4 text-sm text-gray-600 text-center">
        Note: We only ship to addresses in India, Malaysia, and Nepal.
      </p>
    </div>
  );
};

export default PaymentComponent;