import React, { Component } from 'react';
import { __ } from '@wordpress/i18n';
import { PartyPopper, Calendar, Clock, BriefcaseBusiness, User, Mail, Phone, Globe, Contact, CircleDollarSign, ChevronUp, CalendarPlus } from 'lucide-react';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

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

class ConfirmationStep extends Component {
  state = {
    animateIn: false,
    isDrawerOpen: false,
  };

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

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

  handleBookAnother = () => {
    window.location.reload();
  };

  toggleDrawer = () => {
    this.setState((prevState) => ({ isDrawerOpen: !prevState.isDrawerOpen }));
  };

  addToGoogleCalendar = async () => {
    const { state } = this.props;

    try {
      const res = await fetch(`${wpbApp.root}bookify/v1/add-to-gcal`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpbApp.nonce,
        },
        body: JSON.stringify({
          appointment_id: state.appointmentId,
          redirect_url: window.location.origin + window.location.pathname,
        }),
      });

      const data = await res.json();
      if (data.success && data.url) {
        window.location.href = data.url;
      }
    } catch (error) {
      console.error('Error adding to Google Calendar:', error);
    }
  };

  addToOutlookCalendar = async () => {
    const { state } = this.props;

    try {
      const res = await fetch(`${wpbApp.root}bookify/v1/add-to-ocal`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpbApp.nonce,
        },
        body: JSON.stringify({
          appointment_id: state.appointmentId,
          redirect_url: window.location.origin + window.location.pathname,
        }),
      });

      const data = await res.json();
      if (data.success && data.url) {
        window.location.href = data.url;
      }
    } catch (error) {
      console.error('Error adding to Outlook Calendar:', error);
    }
  };

  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,
  });

  getSlotLabel = () => {
    const { state } = this.props;
    if (!state.slot || !state.timezone) return '';
    const tf = state.timeFormat === 'HH:mm' ? 'HH:mm' : 'hh:mm A';

    const convertSlotToUserTimezone = (slot) => {
      const [start, end] = slot.split(' - ');
      const formatedStartTime = dayjs(`1970-01-01 ${start}`).format('HH:mm');
      const formatedEndTime = dayjs(`1970-01-01 ${end}`).format('HH:mm');
      const startTime = dayjs.tz(`1970-01-01 ${formatedStartTime}`, wpbApp.wpTimezone).tz(state.timezone);
      const endTime = dayjs.tz(`1970-01-01 ${formatedEndTime}`, wpbApp.wpTimezone).tz(state.timezone);
      return `${startTime.format(tf)} - ${endTime.format(tf)}`;
    };

    return (state.slot || []).map(convertSlotToUserTimezone).join(' | ');
  };

  render() {
    const { state, data } = this.props;
    const { isDrawerOpen } = this.state;
    const slotLabel = this.getSlotLabel();
    const showCalendarOptions = window.IntegrationSettings && (data?.gcalForCustomer || data?.ocalForCustomer);

    return (
      <>
        <div className={`max-w-2xl min-h-auto text-center space-y-4 animate-in duration-500 p-5 relative ${isDrawerOpen ? 'blur-[2px]' : ''}`}>
          <div className="flex flex-col items-center" style={this.blockStyle(0)}>
            <div className="w-14 h-14 bg-green-100 text-green-600 rounded-full flex items-center justify-center mb-3 animate-bounce">
              <PartyPopper size={28} />
            </div>
            <h3 className="text-xl font-black text-slate-800">{this.applyFilters('bookify_confirmation_section_congrats_text', __('Congratulations', 'bookify'))}</h3>
            <p className="text-base text-slate-500 mt-2">{this.applyFilters('bookify_confirmation_section_message', __('Your appointment has been successfully scheduled.', 'bookify'))}</p>
            <div className="mt-4 px-6 py-2 bg-blue-50 text-blue-600 rounded-full font-bold text-sm tracking-wide border border-blue-100" style={this.blockStyle(60)}>
              {this.applyFilters('bookify_confirmation_section_appointment_id_label', __('Appointment ID #', 'bookify'))}
              {state.appointmentId}
            </div>
          </div>

          <div className="bg-white rounded-3xl p-6 border border-slate-100 shadow-sm text-left space-y-8" style={this.blockStyle(120)}>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div className="space-y-4">
                <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-50 pb-2">
                  {this.applyFilters('bookify_confirmation_section_booking_details_title', __('Booking Details', 'bookify'))}
                </h4>
                <div className="space-y-3">
                  {this.applyFilters('bookify_confirmation_section_date_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(180)}>
                      <Calendar size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{state.date}</span>
                    </div>
                  )}
                  {this.applyFilters('bookify_confirmation_section_local_time_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(220)}>
                      <Clock size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{slotLabel}</span>
                    </div>
                  )}
                  {this.applyFilters('bookify_confirmation_section_timezone_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(260)}>
                      <Globe size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{state.timezone}</span>
                    </div>
                  )}
                  {this.applyFilters('bookify_confirmation_section_service_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(300)}>
                      <BriefcaseBusiness size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{state.serviceName}</span>
                    </div>
                  )}
                  {this.applyFilters('bookify_confirmation_section_employee_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(340)}>
                      <Contact size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{state.staffName}</span>
                    </div>
                  )}
                  {this.applyFilters('bookify_confirmation_section_payment_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(380)}>
                      <CircleDollarSign size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{state.currencySymbol + " " + state.total}
                      </span>
                    </div>
                  )}
                </div>
              </div>

              <div className="space-y-4" style={this.blockStyle(120)}>
                <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-50 pb-2">
                  {this.applyFilters('bookify_confirmation_section_client_details_title', __('Client Details', 'bookify'))}
                </h4>
                <div className="space-y-3">
                  {this.applyFilters('bookify_confirmation_section_name_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(180)}>
                      <User size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{state.firstName} {state.lastName}</span>
                    </div>
                  )}
                  {this.applyFilters('bookify_confirmation_section_email_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(220)}>
                      <Mail size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 break-all max-w-[11em]">{state.email}</span>
                    </div>
                  )}
                  {this.applyFilters('bookify_confirmation_section_phone_show', true) && (
                    <div className="flex items-center space-x-3" style={this.blockStyle(260)}>
                      <Phone size={18} className="text-blue-500" />
                      <span className="text-sm font-medium text-slate-700 max-w-[11em]">{state.phone}</span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

        </div>

        <div className="px-[20px] py-[10px] flex justify-end mt-auto sticky bottom-0 bg-white border-t border-slate-150 relative overflow-visible">
          {showCalendarOptions && (
            <div
              className={`absolute left-0 w-full bottom-full bg-white rounded-t-lg border border-slate-150 shadow-[0_-3px_15px_3px_rgb(0_0_0_/_0.1)] transition-all duration-400 ease-in-out ${
                isDrawerOpen
                  ? 'opacity-100 translate-y-0 visible'
                  : 'opacity-0 translate-y-2 invisible pointer-events-none'
              }`}
              style={{ zIndex: 900 }}
            >
              <div className="px-5 py-5">
                <div className="text-center mb-5">
                  <h3 className="text-base font-semibold text-slate-800 flex items-center justify-center gap-2 mb-1">
                    <CalendarPlus size={20} className="text-blue-600" />
                    {__('Add to Your Calendar', 'bookify')}
                  </h3>
                  <p className="text-xs text-slate-500">{__('Never miss your appointment', 'bookify')}</p>
                </div>

                <div className="flex flex-wrap justify-center gap-4 max-w-2xl mx-auto">
                  {data?.gcalForCustomer && (
                    <button
                      onClick={this.addToGoogleCalendar}
                      className="flex items-center gap-2 px-3 py-2 bg-white border border-slate-200 rounded-lg hover:border-blue-500 hover:shadow-md transition-all group min-w-[200px]"
                    >
                      <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center flex-shrink-0">
                        <svg className="w-6 h-6" viewBox="0 0 24 24">
                          <path
                            fill="#4285F4"
                            d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
                          />
                          <path
                            fill="#34A853"
                            d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
                          />
                          <path
                            fill="#FBBC05"
                            d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
                          />
                          <path
                            fill="#EA4335"
                            d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
                          />
                        </svg>
                      </div>
                      <div className="text-left flex-1">
                        <div className="text-sm font-semibold text-slate-800">{__('Google Calendar', 'bookify')}</div>
                        <div className="text-xs text-slate-500">{__('Sync with Google', 'bookify')}</div>
                      </div>
                    </button>
                  )}

                  {data?.ocalForCustomer && (
                    <button
                      onClick={this.addToOutlookCalendar}
                      className="flex items-center gap-2 px-3 py-2 bg-white border border-slate-200 rounded-lg hover:border-blue-500 hover:shadow-md transition-all group min-w-[200px]"
                    >
                      <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center flex-shrink-0">
                        <svg className="w-6 h-6" viewBox="0 0 24 24">
                          <path
                            fill="#0078D4"
                            d="M3 3v18h18V3H3zm16 16H5V5h14v14z"
                          />
                          <path
                            fill="#0078D4"
                            d="M7 7h10v2H7zm0 4h10v2H7zm0 4h7v2H7z"
                          />
                        </svg>
                      </div>
                      <div className="text-left flex-1">
                        <div className="text-sm font-semibold text-slate-800">{__('Outlook Calendar', 'bookify')}</div>
                        <div className="text-xs text-slate-500">{__('Sync with Outlook', 'bookify')}</div>
                      </div>
                    </button>
                  )}
                </div>
              </div>
            </div>
          )}
          
          <div className="flex items-center justify-end gap-2">
            <button
              onClick={this.handleBookAnother}
              className="px-[16px] py-[6px] text-slate-400 text-sm font-bold rounded-sm hover:bg-slate-50 transition-colors"
            >
              <span>{this.applyFilters('bookify_confirmation_section_book_another_label', __('Book Another', 'bookify'))}</span>
            </button>
            {showCalendarOptions && (
              <button
                onClick={this.toggleDrawer}
                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 transition-all flex items-center gap-2"
              >
                <CalendarPlus size={16} />
                <span>{__('Add to Calendar', 'bookify')}</span>
              </button>
            )}
          </div>
        </div>
      </>
    );
  }
}

export default ConfirmationStep;
