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

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

const PaymentComponent = ({ amount, onSuccess }) => {
  const [error, setError] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [usdAmount, setUsdAmount] = useState(null);

  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: "9bcb30907dee1cda9866f7b49f0f8def",
            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 handleApprove = 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);
    }
  };

  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>
      )}
      <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",
              },
            });
          }}
          onShippingChange={(data, actions) => {
            const allowedCountries = ["IN", "MY", "NP"];
            const shippingCountry = data.shipping_address.country_code;

            if (!allowedCountries.includes(shippingCountry)) {
              return actions.reject().then(() => {
                setError(
                  "Shipping is only available for India, Malaysia, and Nepal. Please update your address."
                );
              });
            }
            return actions.resolve();
          }}
          onApprove={handleApprove}
          onError={(err) => {
            setError("Payment failed. Please try again.");
          }}
        />

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

export default PaymentComponent;
