import React, { Component } from 'react';
import { __ } from '@wordpress/i18n';
import { CreditCard, Wallet, CheckCircle2, AlertCircle } from 'lucide-react';
import PaypalGateway from '../../PaypalGateway';
import Skeleton from '@mui/material/Skeleton';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

dayjs.extend(utc);
dayjs.extend(timezone);

class PaymentStep extends Component {
  state = {
    loading: false,
    error: null,
    paymentSettings: null,
    paymentLoading: true,
    allGatewaysDisabled: false,
    animateIn: false,
  };

  componentDidMount() {
    this.fetchPaymentSettings();
    requestAnimationFrame(() => this.setState({ animateIn: true }));
  }

  componentDidUpdate() {}

  applyFilters = (hook, value, ...args) => {
    const hooks = globalThis?.wp?.hooks;
    return hooks?.applyFilters ? hooks.applyFilters(hook, value, ...args) : value;
  };

  fetchPaymentSettings = async () => {
    try {
      this.setState({ paymentLoading: true });
      const res = await fetch(`${wpbApp.root}bookify/frontend/v1/payment-settings`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpbApp.nonce,
        },
      });
      const data = await res.json();
      const parsed = data?.payment || {};

      const allOff = Object.keys(parsed).length === 0 || Object.keys(parsed).every((key) => !parsed[key]?.toggled);

      this.setState({
        paymentSettings: parsed,
        allGatewaysDisabled: allOff,
      });

      if (!allOff) {
        const onsiteOn = parsed?.onsite?.toggled;
        const paypalOn = parsed?.paypal?.toggled;
        const stripeOn = parsed?.stripe?.toggled;
        const current = this.props.state.gateway;
        const pick = onsiteOn ? 'on-site' : paypalOn ? 'paypal' : stripeOn ? 'stripe' : current;
        if (!current || (current === 'on-site' && !onsiteOn) || (current === 'paypal' && !paypalOn) || (current === 'stripe' && !stripeOn)) {
          this.props.updateInput('gateway', pick);
        }
      }
    } catch (err) {
      console.error('Error fetching payment settings:', err);
      this.setState({ allGatewaysDisabled: true });
    } finally {
      this.setState({ paymentLoading: false });
    }
  };

  blockStyle = (delay = 0) => ({
    transition: 'opacity 600ms ease, transform 600ms ease',
    transitionDelay: `${delay}ms`,
    transform: this.state.animateIn ? 'translateY(0)' : 'translateY(24px)',
    opacity: this.state.animateIn ? 1 : 0,
  });

  selectPayment = (method) => {
    this.props.updateInput('gateway', method);
  };

  getSlotLabel = () => {
    const { state } = this.props;
    if (!state.slot || !state.timezone) return [];
    const tf = state.timeFormat === 'HH:mm' ? 'HH:mm' : 'hh:mm A';
    const convert = (slot) => {
      const [start, end] = slot.split(' - ');
      const startTime = dayjs.tz(`1970-01-01 ${start}`, wpbApp.wpTimezone).tz(state.timezone);
      const endTime = dayjs.tz(`1970-01-01 ${end}`, wpbApp.wpTimezone).tz(state.timezone);
      return `${startTime.format(tf)} - ${endTime.format(tf)}`;
    };
    return (state.slot || []).map(convert);
  };

  getTotalAmount = () => {
    const { state } = this.props;
    if (state.total) return state.total;
    return state.servicePrice || 0;
  };

  completeBooking = async (paidAmount) => {
    const { state, updateInput, onNext } = this.props;
    this.setState({ loading: true, error: null });

    try {
      const payload = {
        location_id: state.locationId || wpbApp?.Locations?.[0] || null,
        service_id: state.serviceId || wpbApp?.Services?.[0] || null,
        staff_id: state.staffId || wpbApp?.Staffs?.[0] || null,
        date: state.date,
        slot: state.slot,
        first_name: state.firstName,
        last_name: state.lastName,
        email: state.email,
        phone: state.phone,
        note: state.note,
        gateway: state.gateway,
        customer_id: state.customerId,
        total: this.getTotalAmount(),
        timezone: state.timezone,
      };

      if (typeof paidAmount !== 'undefined') {
        payload.paidAmount = paidAmount;
      }

      const res = await fetch(`${wpbApp.root}bookify/frontend/v1/add-appointment`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpbApp.nonce,
        },
        body: JSON.stringify(payload),
      });
      const json = await res.json();
      if (json.success) {
        updateInput('appointmentId', json.appointment_id);
        onNext();
      } else {
        this.setState({ error: json.message || __('Unable to complete booking.', 'bookify') });
      }
    } catch (err) {
      console.error('Error submitting booking:', err);
      this.setState({ error: __('Unable to complete booking. Please try again.', 'bookify') });
    } finally {
      this.setState({ loading: false });
    }
  };

  render() {
    const { state, onBack, updateInput } = this.props;
    const { loading, error, paymentSettings, paymentLoading, allGatewaysDisabled } = this.state;
    const slotObjects = this.getSlotLabel();
    const slotLabel = slotObjects.join(' | ');
    const totalAmount = this.getTotalAmount();
    const eachPrice = totalAmount / (state.slot ? slotObjects.length : 1);

    return (
      <>
        <div className="flex flex-col min-h-auto max-w-3xl space-y-4 animate-in fade-in slide-in-from-right-4 duration-500 p-5">
          <div className="bg-slate-50 rounded-3xl p-8 border border-slate-100 shadow-sm" style={this.blockStyle(0)}>
            <div className="flex justify-between items-center pb-[14px] border-b border-slate-200" style={this.blockStyle(40)}>
              <div className="w-full">
                <h4 className="text-xs font-semibold text-slate-400 uppercase tracking-widest mb-1">{__('Service', 'bookify')}</h4>
                <div>
                  <p className="text-sm font-normal text-slate-800">{state.serviceName + " is scheduled for " + state.date + " at: "}</p>
                  {slotObjects.map((eachSlot, index) => (
                    <div key={index} className="flex justify-between items-center py-1 px-4">
                      <div className="text-sm text-slate-800" style={{ color: '#292D32' }}>{eachSlot}</div>
                      {wp.hooks.applyFilters('bookify_payment_section_service_price_show', true) && (
                        <div className="text-sm font-semibold text-slate-800">
                          {(state.currencySymbol || '$') + eachPrice}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>
            {this.applyFilters('bookify_payment_section_subtotal_show', true) && (
              <div className="py-[14px] text-sm font-medium flex justify-between" style={this.blockStyle(80)}>
                <span className="text-slate-800">{__('Subtotal', 'bookify')}</span>
                <span className="text-sm font-semibold text-slate-800">
                  {(state.currencySymbol || '$') + totalAmount}
                </span>
              </div>
            )}
            {this.applyFilters('bookify_payment_section_total_show', true) && (
              <div className="flex justify-between items-center border-t border-slate-200 pt-[14px]" style={this.blockStyle(120)}>
                <span className="font-medium text-slate-800 text-base">{__('Total Amount', 'bookify')}</span>
                <span className="font-semibold text-blue-600 text-base">
                  {(state.currencySymbol || '$') + totalAmount}
                </span>
              </div>
            )}
          </div>

          {this.applyFilters('bookify_payment_section_gateways_show', true) && (
            <div className="space-y-3" style={this.blockStyle(60)}>
              <h3 className="text-lg font-semibold text-slate-800 ml-1">{__('Select Payment Method', 'bookify')}</h3>
              <div className="grid grid-cols-1 gap-4">
                {paymentLoading && (
                  <>
                    {Array.from({ length: 3 }).map((_, idx) => (
                      <div key={idx} className="px-5 py-3 rounded-2xl border-2 border-slate-100 bg-white">
                        <div className="flex items-center gap-4">
                          <Skeleton variant="rounded" width={40} height={40} />
                          <div className="flex-1">
                            <Skeleton variant="text" width="45%" height={20} />
                            <Skeleton variant="text" width="70%" height={16} />
                          </div>
                          <Skeleton variant="circular" width={20} height={20} />
                        </div>
                      </div>
                    ))}
                  </>
                )}

                {!paymentLoading && paymentSettings?.onsite?.toggled && (
                  <button
                    onClick={() => this.selectPayment('on-site')}
                    className={`flex items-center px-5 py-3 rounded-2xl border-2 transition-all outline-none ${state.gateway === 'on-site'
                      ? 'border-blue-600 bg-blue-50/50'
                      : 'border-slate-100 bg-white hover:border-blue-200'
                      }`}
                    style={this.blockStyle(120)}
                  >
                    <div
                      className={`p-2 rounded-xl mr-4 ${state.gateway === 'on-site' ? 'bg-blue-600 text-white' : 'bg-slate-100 text-slate-400'
                        }`}
                    >
                      <Wallet size={18} />
                    </div>
                    <div className="flex-1 text-left">
                      <p className="text-base font-medium text-slate-800">{__('Pay on Site', 'bookify')}</p>
                      <p className="text-xs text-slate-500">{__('Secure your slot now, pay when you arrive.', 'bookify')}</p>
                    </div>
                    {state.gateway === 'on-site' && <CheckCircle2 size={20} className="text-blue-600" />}
                  </button>
                )}

                {!paymentLoading && paymentSettings?.paypal?.toggled && (
                  <button
                    onClick={() => this.selectPayment('paypal')}
                    className={`flex flex-col px-5 py-3 rounded-2xl border-2 transition-all outline-none ${state.gateway === 'paypal'
                      ? 'border-blue-600 bg-blue-50/50'
                      : 'border-slate-100 bg-white hover:border-blue-200'
                      }`}
                    style={this.blockStyle(180)}
                  >
                    <div className="flex-1 flex items-center">
                      <div
                        className={`p-2 rounded-xl mr-4 ${state.gateway === 'paypal' ? 'bg-blue-600 text-white' : 'bg-slate-100 text-slate-400'
                          }`}
                      >
                        <CreditCard size={18} />
                      </div>
                      <div className="flex-1 text-left">
                        <p className="text-base font-medium text-slate-800">{__('PayPal (Online)', 'bookify')}</p>
                        <p className="text-xs text-slate-500">{__('Instant confirmation via secure payment.', 'bookify')}</p>
                      </div>
                      {state.gateway === 'paypal' && <CheckCircle2 size={20} className="text-blue-600" />}
                    </div>
                    {!paymentLoading && paymentSettings?.paypal?.toggled && state.gateway === 'paypal' && (
                      <div className="mt-2">
                        <PaypalGateway
                          paymentSettings={paymentSettings}
                          currencyCode={state.currencyCode}
                          contextState={state}
                          submitBooking={this.completeBooking}
                          setError={(message) => this.setState({ error: message })}
                        />
                      </div>
                    )}
                  </button>
                )}

                {window.BookifyPro?.Light?.PaymentGateways && (
                  <window.BookifyPro.Light.PaymentGateways
                    paymentSettings={paymentSettings}
                    currencyCode={state.currencyCode}
                    contextState={state}
                    handleMethodChange={(method) => this.selectPayment(method)}
                    submitBooking={this.completeBooking}
                    setState={(newState) => this.setState(newState)}
                    blockStyle={this.blockStyle}
                  />
                )}

                {this.applyFilters(
                  'bookify_add_payment_gateway',
                  [],
                  paymentSettings,
                  state.currencyCode,
                  (method) => this.selectPayment(method),
                  this.completeBooking,
                  state,
                  updateInput,
                  { paymentLoading, allGatewaysDisabled },
                  (message) => this.setState({ error: message })
                )}

                {!paymentLoading && allGatewaysDisabled && (
                  <div className="flex items-center space-x-2 text-red-500 text-sm bg-red-50 border border-red-100 rounded-2xl px-4 py-3">
                    <AlertCircle size={18} />
                    <span>{__('No payment method available.', 'bookify')}</span>
                  </div>
                )}
              </div>
            </div>
          )}

          {error && (
            <div
              className="flex items-center space-x-2 text-red-500 text-sm bg-red-50 border border-red-100 rounded-2xl px-4 py-3"
              style={this.blockStyle(240)}
            >
              <AlertCircle size={18} />
              <span>{error}</span>
            </div>
          )}
        </div>

        <div className="z-[999] px-[20px] py-[10px] flex justify-end mt-auto sticky bottom-0 bg-white border-t border-slate-150">
          <button
            onClick={onBack}
            className="px-[16px] py-[6px] text-slate-400 text-sm font-bold rounded-sm hover:bg-slate-50 transition-colors"
          >
            {__('Back', 'bookify')}
          </button>
          {(state.gateway === "on-site") && (
            <button
              onClick={() => this.completeBooking()}
              disabled={loading || paymentLoading || allGatewaysDisabled}
              className="px-[16px] py-[6px] bg-blue-600 text-white text-sm font-bold rounded-sm shadow-xl shadow-blue-200 hover:bg-blue-700 disabled:opacity-50 disabled:shadow-none transition-all"
            >
              <span>
                {loading
                  ? this.applyFilters('bookify_submit_button_loading_text', __('Loading...', 'bookify'))
                  : this.applyFilters('bookify_submit_button_text', __('Submit', 'bookify'))}
              </span>
            </button>
          )}
        </div>
      </>
    );
  }
}

export default PaymentStep;
