import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { __ } from '@wordpress/i18n';
import { LocationWithRole } from '../../../types/location.entity';
import { UserRoleType } from '../../../types/user.entity';
import { InviteOwnerDialog } from './dialogs/invite-owner-dialog';
import { App } from '../../../app';
import { ActionItem } from './components/action-item/action-item';
import { apiService } from '../../../services/api.service';
import { LocationHeader } from '../location-header/location-header';
import { AuthFooter } from '../../auth/auth-footer/auth-footer';

interface OverviewProps {
  locationWithRole: LocationWithRole;
  bookingAppUrl: string;
  embedsPageUrl: string;
}

function Overview({ locationWithRole, bookingAppUrl, embedsPageUrl }: OverviewProps): JSX.Element {
  const { location, roles, ownerExpert } = locationWithRole;
  const role = roles[0];
  const [isInviteDialogOpen, setIsInviteDialogOpen] = useState<boolean>(false);
  const [inviteButtonText, setInviteButtonText] = useState<string>(__('Invite Owner', 'timetailor-salon-booking'));
  const [isInviteButtonDisabled, setIsInviteButtonDisabled] = useState<boolean>(false);
  const [locationAuthLinkLoading, setLocationAuthLinkLoading] = useState<boolean>(false);
  const [userAuthLinkLoading, setUserAuthLinkLoading] = useState<boolean>(false);

  const handleInviteSuccess = (): void => {
    setInviteButtonText(__('Invitation sent', 'timetailor-salon-booking'));
    setIsInviteButtonDisabled(true);

    window.setTimeout(() => {
      setInviteButtonText(__('Invite Owner', 'timetailor-salon-booking'));
      setIsInviteButtonDisabled(false);
    }, 5000);
  };

  const handleGetLocationAuthLink = async (): Promise<void> => {
    setLocationAuthLinkLoading(true);
    try {
      const result = await apiService.getLocationAuthLink(location.id);
      if (result?.authLink) {
        window.open(result.authLink, '_blank');
      }
    } catch (err) {
      alert(__('Failed to get dashboard link. Please try again.', 'timetailor-salon-booking'));
    } finally {
      setLocationAuthLinkLoading(false);
    }
  };

  const handleGetUserAuthLink = async (): Promise<void> => {
    setUserAuthLinkLoading(true);
    try {
      const result = await apiService.getUserAuthLink();
      if (result?.authLink) {
        window.open(result.authLink, '_blank');
      }
    } catch (err) {
      alert(__('Failed to get auth link. Please try again.', 'timetailor-salon-booking'));
    } finally {
      setUserAuthLinkLoading(false);
    }
  };

  return (
    <>
      <div className="flex flex-col items-center">
        <div className="w-full max-w-3xl flex flex-col bg-white shadow rounded-lg border border-gray-300">
          <h2 className="text-lg font-medium px-6 py-4">{__('Things to do next', 'timetailor-salon-booking')}</h2>

          <ActionItem
            icon="play"
            title={__('Test Booking Flow', 'timetailor-salon-booking')}
            description={__('Test your booking process by creating a test booking.', 'timetailor-salon-booking')}
            action={
              <a
                href={App.getLocationBookingUrl(location.uuid, true)}
                target="_blank"
                rel="noopener noreferrer"
                className="button button-large min-w-40 text-center"
              >
                {__('Test Booking', 'timetailor-salon-booking')}
              </a>
            }
          />

          {role === UserRoleType.LocationOwner && (
            <ActionItem
              icon="settings"
              title={__('Complete Your Setup', 'timetailor-salon-booking')}
              description={__(
                'Set up your business details, services, hours, and booking preferences.',
                'timetailor-salon-booking',
              )}
              action={
                <button
                  className="button button-large min-w-40 text-center"
                  onClick={handleGetLocationAuthLink}
                  disabled={locationAuthLinkLoading}
                >
                  {locationAuthLinkLoading
                    ? __('Loading...', 'timetailor-salon-booking')
                    : __('Complete Setup', 'timetailor-salon-booking')}
                </button>
              }
            />
          )}

          <ActionItem
            icon="code"
            title={__('Embed Widget on a Page', 'timetailor-salon-booking')}
            description={__(
              'Add the booking widget to any page using our shortcode or block.',
              'timetailor-salon-booking',
            )}
            action={
              <a href={embedsPageUrl} className="button button-large min-w-40 text-center">
                {__('Embed Widget', 'timetailor-salon-booking')}
              </a>
            }
          />

          {role === UserRoleType.PartnerOwner && (
            <>
              <ActionItem
                icon="userAdd"
                title={__('Invite Salon Owner', 'timetailor-salon-booking')}
                description={__(
                  'Give the salon owner access so they can finish setup and manage bookings and payments.',
                  'timetailor-salon-booking',
                )}
                action={
                  <button
                    className="button button-large min-w-40 text-center"
                    onClick={() => setIsInviteDialogOpen(true)}
                    disabled={isInviteButtonDisabled}
                  >
                    {inviteButtonText}
                  </button>
                }
              />

              <ActionItem
                icon="shield"
                title={__('Learn About Your Partner Account', 'timetailor-salon-booking')}
                description={__(
                  'See how your partner dashboard helps you manage salon accounts and track your earnings.',
                  'timetailor-salon-booking',
                )}
                action={
                  <button
                    className="button button-large min-w-40 text-center"
                    onClick={handleGetUserAuthLink}
                    disabled={userAuthLinkLoading}
                  >
                    {userAuthLinkLoading
                      ? __('Loading...', 'timetailor-salon-booking')
                      : __('Open PartnerHub', 'timetailor-salon-booking')}
                  </button>
                }
              />
            </>
          )}
        </div>
      </div>

      <InviteOwnerDialog
        isOpen={isInviteDialogOpen}
        onClose={() => setIsInviteDialogOpen(false)}
        locationId={location.id}
        expertId={ownerExpert.id}
        defaultFirstName={ownerExpert.firstName || ''}
        onSuccess={handleInviteSuccess}
      />
    </>
  );
}

function initOverview(): void {
  const container = document.getElementById('ttsbs-overview-root');
  if (!container) {
    return;
  }

  // init the app
  App.bootstrap({
    ajaxUrl: container.dataset.ajaxUrl || '',
    nonce: container.dataset.nonce || '',
    bookingAppUrl: container.dataset.bookingAppUrl || '',
  });

  const locationWithRole = JSON.parse(container.dataset.locationWithRole || '{}') as LocationWithRole;
  const bookingAppUrl = container.dataset.bookingAppUrl || '';
  const embedsPageUrl = container.dataset.embedsPageUrl || '';

  const root = createRoot(container);
  root.render(
    <>
      <LocationHeader locationWithRole={locationWithRole} />
      <div className="flex-1">
        <Overview locationWithRole={locationWithRole} bookingAppUrl={bookingAppUrl} embedsPageUrl={embedsPageUrl} />
      </div>
      <AuthFooter />
    </>,
  );
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initOverview);
} else {
  initOverview();
}
