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

const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
const EXCHANGE_RATE_KEY = "exchange_rate_cache";

const PaymentComponent = ({ amount, onSuccess }) => {
  const { error: razorpayError, isLoading, Razorpay } = useRazorpay();
  const [error, setError] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [usdAmount, setUsdAmount] = useState(null);
  const [showPopup, setShowPopup] = useState(false);
  const [shippingData, setShippingData] = useState({
    address_line_1: "",
    address_line_2: "",
    state: "",
    city: "",
    country_code: "",
    postal_code: "",
  });

  useEffect(() => {
    const fetchExchangeRate = async () => {
      try {
        const cachedData = localStorage.getItem(EXCHANGE_RATE_KEY);
        if (cachedData) {
          const { rate, timestamp } = JSON.parse(cachedData);
          if (Date.now() - timestamp < CACHE_DURATION) {
            setUsdAmount((amount * rate).toFixed(2));
            return;
          }
        }

        const response = await axios.get("https://apilayer.net/api/live", {
          params: {
            access_key: "",
            currencies: "USD",
            source: "INR",
            format: 1,
          },
        });

        if (response.data.success) {
          const rate = response.data.quotes.INRUSD;
          localStorage.setItem(
            EXCHANGE_RATE_KEY,
            JSON.stringify({
              rate,
              timestamp: Date.now(),
            })
          );
          setUsdAmount((amount * rate).toFixed(2));
        } else {
          throw new Error("Failed to fetch exchange rate");
        }
      } catch (err) {
        setError("Currency conversion failed. Please try again later.");
        console.error("Exchange rate error:", err);
      }
    };

    fetchExchangeRate();
  }, [amount]);

  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,
      shippingData, // Include the shipping data in the success callback
    });
  };

  const handleRazorpayPayment = async () => {
    if (!shippingData.address_line_1 || !shippingData.city || !shippingData.postal_code) {
      setError("Please fill in all required fields.");
      return;
    }

    try {
      const order = await createOrder();
      console.log(shippingData)
      const options = {
        key: "rzp_test_1SbLmNX2nCKRZA",
        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.city,
        },
        handler: (response) => {
          response.address = shippingData
          handlePaymentSuccess(response); // Pass the response to the success handler
        },
      };

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

  const handlePopupSubmit = () => {
    setShowPopup(false);
    handleRazorpayPayment();
  };

  if (!usdAmount) {
    return <div className="text-center p-4">Loading exchange rates...</div>;
  }

  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>
      )}
      <PayPalScriptProvider
        options={{
          "client-id": process.env.NEXT_PUBLIC_CLIENT_ID,
        }}
      >
        <PayPalButtons
          style={{
            layout: "horizontal",
            label: "checkout",
            tagline: false,
            fundingicons: true,
          }}
          disabled={isProcessing}
          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();
              onSuccess?.(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.");
          }}
        />
      </PayPalScriptProvider>

      <button
        onClick={() => setShowPopup(true)}
        disabled={isProcessing || isLoading}
        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>

      {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"
            />
            <button
              onClick={handlePopupSubmit}
              className="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"
            >
              Submit
            </button>
          </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;