import React, { Component } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { PayPalButtons, PayPalScriptProvider, FUNDING } from '@paypal/react-paypal-js';

class PaypalGateway extends Component {
  supportedCurrencies = [
    'AUD', 'BRL', 'CAD', 'CNY', 'CZK', 'DKK', 'EUR', 'HKD', 'HUF', 'ILS',
    'JPY', 'MYR', 'MXN', 'TWD', 'NZD', 'NOK', 'PHP', 'PLN', 'GBP', 'SGD',
    'SEK', 'CHF', 'THB', 'USD',
  ];

  state = {
    clientId: '',
    enabled: false,
  };

  componentDidMount() {
    this.updateGatewayState();
  }

  componentDidUpdate(prevProps) {
    if (
      prevProps.paymentSettings !== this.props.paymentSettings ||
      prevProps.currencyCode !== this.props.currencyCode
    ) {
      this.updateGatewayState();
    }
  }

  updateGatewayState = () => {
    const { paymentSettings, currencyCode, setError } = this.props;
    const paypalConfig = paymentSettings?.paypal;

    if (!paypalConfig?.clientId) {
      setError(__('PayPal is not configured.', 'bookify'));
      this.setState({ enabled: false, clientId: '' });
      return;
    }

    if (!this.supportedCurrencies.includes(currencyCode)) {
      setError(sprintf(__('Currency %s is not supported for PayPal.', 'bookify'), currencyCode));
      this.setState({ enabled: false, clientId: '' });
      return;
    }

    this.setState({ clientId: paypalConfig.clientId, enabled: true });
    setError(null);
  };

  onCreateOrder = (_data, actions) => {
    const { currencyCode, contextState } = this.props;
    return actions.order.create({
      purchase_units: [
        {
          amount: {
            value: contextState.total,
            currency_code: currencyCode,
            breakdown: {
              item_total: {
                currency_code: currencyCode,
                value: contextState.total,
              },
            },
          },
          items: [
            {
              name: __('WP Bookify - Appointment', 'bookify'),
              quantity: '1',
              description: sprintf(__('WP Bookify - Appointment booked on date: %s', 'bookify'), contextState.date),
              unit_amount: {
                currency_code: currencyCode,
                value: contextState.total,
              },
            },
          ],
        },
      ],
    });
  };

  onApproveOrder = async (_data, actions) => {
    const { contextState, submitBooking, setError } = this.props;

    try {
      const validationPayload = {
        location_id: contextState.locationId,
        service_id: contextState.serviceId,
        staff_id: contextState.staffId,
        date: contextState.date,
        slot: contextState.slot,
        first_name: contextState.firstName,
        last_name: contextState.lastName,
        email: contextState.email,
        phone: contextState.phone,
        note: contextState.note,
        gateway: contextState.gateway,
        customer_id: contextState.customerId,
      };

      const validationRes = await fetch(`${wpbApp.root}bookify/frontend/v1/check-validation`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpbApp.nonce,
        },
        body: JSON.stringify(validationPayload),
      });

      const validationResult = await validationRes.json();
      if (!validationResult.success) {
        setError(validationResult.message || __('Validation failed before payment.', 'bookify'));
        return;
      }

      const details = await actions.order.capture();
      const paidAmount = details?.purchase_units?.[0]?.payments?.captures?.[0]?.amount?.value;
      await submitBooking(paidAmount);
    } catch (err) {
      console.error('Error during PayPal order approval:', err);
      setError(__('An error occurred during PayPal payment. Please try again.', 'bookify'));
    }
  };

  render() {
    const { clientId, enabled } = this.state;
    const { currencyCode, setError } = this.props;

    if (!enabled || !clientId) {
      return null;
    }

    const initialOptions = {
      clientId,
      currency: currencyCode,
      intent: 'capture',
    };

    return (
      <PayPalScriptProvider options={initialOptions}>
        <PayPalButtons
          style={{ layout: 'vertical' }}
          fundingSource={FUNDING.PAYPAL}
          disabled={!enabled}
          createOrder={(data, actions) => this.onCreateOrder(data, actions)}
          onApprove={(data, actions) => this.onApproveOrder(data, actions)}
          onError={() => setError(__('PayPal initialization failed. Please try again.', 'bookify'))}
        />
      </PayPalScriptProvider>
    );
  }
}

export default PaypalGateway;
