import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
    Button,
    TextControl,
    TextareaControl,
    SelectControl,
    Notice,
} from '@wordpress/components';
import api from '../api/client';
import WizardStep from '../components/WizardStep';

/**
 * Calendar SVG icon used on the welcome step.
 */
const CalendarIcon = () => (
    <svg
        xmlns="http://www.w3.org/2000/svg"
        width="48"
        height="48"
        viewBox="0 0 24 24"
        fill="none"
        stroke="#A855F7"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
    >
        <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
        <line x1="16" y1="2" x2="16" y2="6" />
        <line x1="8" y1="2" x2="8" y2="6" />
        <line x1="3" y1="10" x2="21" y2="10" />
        <path d="M8 14h.01M12 14h.01M16 14h.01M8 18h.01M12 18h.01M16 18h.01" />
    </svg>
);

/**
 * Free (this plugin) vs Appointly Pro (separate companion plugin) comparison rows.
 *
 * Everything in this plugin is Free and unlimited. The Pro column describes
 * features delivered by Appointly Pro, a separate companion plugin sold on
 * appointly.tscholene.com (NOT on WordPress.org). Currently shipped Pro
 * features get '\u2713'; planned-but-not-yet-shipped features are labelled
 * 'planned' so we never over-promise on the wizard.
 */
const COMPARISON_ROWS = [
    { feature: __( 'Services & bookings', 'appointly' ), free: __( 'Unlimited', 'appointly' ), pro: __( 'Unlimited', 'appointly' ) },
    { feature: __( 'Personal offer workflow', 'appointly' ), free: '\u2713', pro: '\u2713' },
    { feature: __( 'Automatic offer / confirmation emails', 'appointly' ), free: '\u2713', pro: '\u2713' },
    { feature: __( 'Default email templates (translatable)', 'appointly' ), free: '\u2713', pro: '\u2713' },
    { feature: __( 'SMTP email delivery', 'appointly' ), free: '\u2713', pro: '\u2713' },
    { feature: __( 'Custom branding (colors + logo)', 'appointly' ), free: '\u2014', pro: '\u2713' },
    { feature: __( 'Custom email template editor', 'appointly' ), free: '\u2014', pro: __( 'Live preview', 'appointly' ) },
    { feature: __( 'Custom service fields', 'appointly' ), free: '\u2014', pro: __( 'Field builder', 'appointly' ) },
    { feature: __( 'Service addons (upsells)', 'appointly' ), free: '\u2014', pro: '\u2713' },
    { feature: __( 'Recurring bookings', 'appointly' ), free: '\u2014', pro: __( 'Weekly / bi-weekly / monthly', 'appointly' ) },
    { feature: __( 'Direct booking (auto-confirm)', 'appointly' ), free: '\u2014', pro: '\u2713' },
    { feature: __( 'Blocked dates', 'appointly' ), free: '\u2014', pro: __( '+ date ranges', 'appointly' ) },
    { feature: __( 'Customer self-cancel', 'appointly' ), free: '\u2014', pro: __( 'Direct-booking services', 'appointly' ) },
    { feature: __( 'Booking reminders', 'appointly' ), free: '\u2014', pro: __( 'Planned', 'appointly' ) },
    { feature: __( 'Multi-day bookings', 'appointly' ), free: '\u2014', pro: __( 'Planned', 'appointly' ) },
    { feature: __( 'Group bookings', 'appointly' ), free: '\u2014', pro: __( 'Planned', 'appointly' ) },
    { feature: __( 'Cancellation policies', 'appointly' ), free: '\u2014', pro: __( 'Planned', 'appointly' ) },
    { feature: __( 'Timeslot scheduling', 'appointly' ), free: __( 'Day only', 'appointly' ), pro: __( 'Planned', 'appointly' ) },
];

const TOTAL_STEPS = 4;

/**
 * Inline SMTP test button for the onboarding wizard email step.
 */
function SmtpTestButton( { emailData } ) {
    const [ testing, setTesting ] = useState( false );
    const [ result, setResult ]   = useState( null ); // { type: 'success'|'error', message }

    const handleTest = async () => {
        setTesting( true );
        setResult( null );
        try {
            // Save the current email settings first so the backend has them.
            await api.updateSettings( emailData );
            const res = await api.testSmtp();
            setResult( {
                type: 'success',
                message: res?.message || __( 'SMTP connection successful!', 'appointly' ),
            } );
        } catch ( err ) {
            setResult( {
                type: 'error',
                message: err?.message || __( 'SMTP connection failed.', 'appointly' ),
            } );
        } finally {
            setTesting( false );
        }
    };

    return (
        <div style={ { marginTop: '12px' } }>
            <Button
                variant="secondary"
                onClick={ handleTest }
                isBusy={ testing }
                disabled={ testing }
                size="small"
            >
                { testing
                    ? __( 'Testing…', 'appointly' )
                    : __( 'Test Connection', 'appointly' ) }
            </Button>
            { result && (
                <p style={ {
                    marginTop: '8px',
                    fontSize: '13px',
                    color: result.type === 'success' ? '#059669' : '#DC2626',
                } }>
                    { result.message }
                </p>
            ) }
        </div>
    );
}

export default function SetupWizard() {
    const [ step, setStep ]               = useState( 0 );
    const [ serviceData, setServiceData ] = useState( {
        title: '',
        description: '',
    } );
    const [ emailData, setEmailData ] = useState( {
        admin_email: window.appointlyAdmin?.adminEmail || '',
        smtp_host: '',
        smtp_port: 587,
        smtp_encryption: 'tls',
        smtp_user: '',
        smtp_pass: '',
    } );
    const [ saving, setSaving ]     = useState( false );
    const [ error, setError ]       = useState( null );

    /**
     * Save the first service.
     */
    const handleSaveService = async () => {
        if ( ! serviceData.title.trim() ) {
            setError( __( 'Please enter a service name.', 'appointly' ) );
            return;
        }
        setSaving( true );
        setError( null );
        try {
            await api.createService( serviceData );
            setStep( 2 );
        } catch ( err ) {
            setError( err?.message || __( 'Failed to create service.', 'appointly' ) );
        } finally {
            setSaving( false );
        }
    };

    /**
     * Save email settings.
     */
    const handleSaveEmail = async () => {
        setSaving( true );
        setError( null );
        try {
            await api.updateSettings( emailData );
            setStep( 3 );
        } catch ( err ) {
            setError( err?.message || __( 'Failed to save email settings.', 'appointly' ) );
        } finally {
            setSaving( false );
        }
    };

    /**
     * Complete onboarding and redirect to the admin dashboard.
     */
    const handleFinish = async () => {
        setSaving( true );
        setError( null );
        try {
            await api.updateSettings( { onboarding_completed: true } );
            window.location.href = window.appointlyAdmin?.adminUrl
                ? window.appointlyAdmin.adminUrl + 'admin.php?page=appointly-dashboard'
                : '/wp-admin/admin.php?page=appointly-dashboard';
        } catch ( err ) {
            setError( err?.message || __( 'Failed to complete setup.', 'appointly' ) );
            setSaving( false );
        }
    };

    return (
        <div className="appointly-wizard">
            { error && (
                <Notice status="error" isDismissible onDismiss={ () => setError( null ) }>
                    { error }
                </Notice>
            ) }

            { /* Step 0: Welcome */ }
            { step === 0 && (
                <WizardStep
                    step={ 0 }
                    totalSteps={ TOTAL_STEPS }
                    title={ __( 'Welcome to Appointly', 'appointly' ) }
                    onNext={ () => setStep( 1 ) }
                    nextLabel={ __( "Let's go →", 'appointly' ) }
                    loading={ false }
                >
                    <div style={ { textAlign: 'center', marginBottom: '24px' } }>
                        <CalendarIcon />
                    </div>
                    <p style={ { textAlign: 'center', color: '#64748b', marginBottom: '24px' } }>
                        { __( "The booking plugin built around a personal offer workflow. Let's set up your first service in a few quick steps.", 'appointly' ) }
                    </p>

                    <div className="appointly-wizard__comparison">
                        <table>
                            <thead>
                                <tr>
                                    <th>{ __( 'Feature', 'appointly' ) }</th>
                                    <th>{ __( 'Appointly (free)', 'appointly' ) }</th>
                                    <th>{ __( 'Appointly Pro', 'appointly' ) }</th>
                                </tr>
                            </thead>
                            <tbody>
                                { COMPARISON_ROWS.map( ( row, idx ) => (
                                    <tr key={ idx }>
                                        <td>{ row.feature }</td>
                                        <td>{ row.free }</td>
                                        <td><strong>{ row.pro }</strong></td>
                                    </tr>
                                ) ) }
                            </tbody>
                        </table>
                        <p className="appointly-wizard__comparison-note">
                            { __( 'Appointly Pro is a separate companion plugin that extends Appointly — €2.99 per month, cancel anytime. Available at appointly.tscholene.com.', 'appointly' ) }
                        </p>
                    </div>
                </WizardStep>
            ) }

            { /* Step 1: First Service */ }
            { step === 1 && (
                <WizardStep
                    step={ 1 }
                    totalSteps={ TOTAL_STEPS }
                    title={ __( 'Create Your First Service', 'appointly' ) }
                    onNext={ handleSaveService }
                    onBack={ () => { setError( null ); setStep( 0 ); } }
                    nextLabel={ __( 'Next', 'appointly' ) }
                    loading={ saving }
                >
                    <TextControl
                        label={ __( 'Service name', 'appointly' ) }
                        value={ serviceData.title }
                        onChange={ ( val ) => setServiceData( { ...serviceData, title: val } ) }
                        placeholder={ __( 'e.g. 60-minute consultation', 'appointly' ) }
                        __next40pxDefaultSize={ true }
                        __nextHasNoMarginBottom={ true }
                    />
                    <TextareaControl
                        label={ __( 'Description (optional)', 'appointly' ) }
                        value={ serviceData.description }
                        onChange={ ( val ) => setServiceData( { ...serviceData, description: val } ) }
                        rows={ 3 }
                        __nextHasNoMarginBottom={ true }
                    />
                </WizardStep>
            ) }

            { /* Step 2: Email */ }
            { step === 2 && (
                <WizardStep
                    step={ 2 }
                    totalSteps={ TOTAL_STEPS }
                    title={ __( 'Email Settings', 'appointly' ) }
                    onNext={ handleSaveEmail }
                    onBack={ () => { setError( null ); setStep( 1 ); } }
                    onSkip={ () => { setError( null ); setStep( 3 ); } }
                    nextLabel={ emailData.smtp_host ? __( 'Save & Next', 'appointly' ) : __( 'Next', 'appointly' ) }
                    loading={ saving }
                >
                    <TextControl
                        label={ __( 'Admin email', 'appointly' ) }
                        value={ emailData.admin_email }
                        onChange={ ( val ) => setEmailData( { ...emailData, admin_email: val } ) }
                        type="email"
                        help={ __( 'Booking notifications will be sent to this address.', 'appointly' ) }
                        __next40pxDefaultSize={ true }
                        __nextHasNoMarginBottom={ true }
                    />
                    <div className="appointly-wizard__smtp-section">
                        <h4>{ __( 'SMTP Configuration', 'appointly' ) }</h4>
                        <p className="appointly-wizard__smtp-desc">
                            { __( 'SMTP ensures your booking emails actually reach customers. Select your email provider to auto-fill the settings.', 'appointly' ) }
                        </p>
                        <SelectControl
                            label={ __( 'Email Provider', 'appointly' ) }
                            value=""
                            options={ [
                                { value: '', label: __( 'Select provider…', 'appointly' ) },
                                { value: 'gmail', label: 'Gmail (Google)' },
                                { value: 'outlook', label: 'Outlook / Microsoft 365' },
                                { value: 'yahoo', label: 'Yahoo Mail' },
                                { value: 'icloud', label: 'iCloud (Apple)' },
                                { value: 'ionos', label: 'IONOS (1&1)' },
                                { value: 'strato', label: 'Strato' },
                                { value: 'world4you', label: 'World4You' },
                                { value: 'hosteurope', label: 'Host Europe' },
                                { value: 'allinkl', label: 'ALL-INKL' },
                                { value: 'hetzner', label: 'Hetzner' },
                                { value: 'zoho', label: 'Zoho Mail' },
                                { value: 'custom', label: __( 'Other / Custom', 'appointly' ) },
                            ] }
                            onChange={ ( provider ) => {
                                const presets = {
                                    gmail:      { smtp_host: 'smtp.gmail.com',       smtp_port: 587, smtp_encryption: 'tls' },
                                    outlook:    { smtp_host: 'smtp.office365.com',   smtp_port: 587, smtp_encryption: 'tls' },
                                    yahoo:      { smtp_host: 'smtp.mail.yahoo.com',  smtp_port: 587, smtp_encryption: 'tls' },
                                    icloud:     { smtp_host: 'smtp.mail.me.com',     smtp_port: 587, smtp_encryption: 'tls' },
                                    ionos:      { smtp_host: 'smtp.ionos.de',        smtp_port: 587, smtp_encryption: 'tls' },
                                    strato:     { smtp_host: 'smtp.strato.de',       smtp_port: 465, smtp_encryption: 'ssl' },
                                    world4you:  { smtp_host: 'smtp.world4you.com',   smtp_port: 587, smtp_encryption: 'tls' },
                                    hosteurope: { smtp_host: 'smtp.hosteurope.de',   smtp_port: 587, smtp_encryption: 'tls' },
                                    allinkl:    { smtp_host: 'smtp.all-inkl.com',    smtp_port: 587, smtp_encryption: 'tls' },
                                    hetzner:    { smtp_host: 'smtp.your-server.de',  smtp_port: 587, smtp_encryption: 'tls' },
                                    zoho:       { smtp_host: 'smtp.zoho.eu',         smtp_port: 587, smtp_encryption: 'tls' },
                                };
                                const preset = presets[ provider ];
                                if ( preset ) {
                                    setEmailData( ( prev ) => ( { ...prev, ...preset } ) );
                                }
                            } }
                            __next40pxDefaultSize={ true }
                            __nextHasNoMarginBottom={ true }
                        />
                        { emailData.smtp_host && (
                            <>
                                <TextControl
                                    label={ __( 'SMTP Host', 'appointly' ) }
                                    value={ emailData.smtp_host }
                                    onChange={ ( val ) => setEmailData( { ...emailData, smtp_host: val } ) }
                                    __next40pxDefaultSize={ true }
                                    __nextHasNoMarginBottom={ true }
                                />
                                <TextControl
                                    label={ __( 'Username (Email)', 'appointly' ) }
                                    value={ emailData.smtp_user }
                                    onChange={ ( val ) => setEmailData( { ...emailData, smtp_user: val } ) }
                                    placeholder="you@example.com"
                                    __next40pxDefaultSize={ true }
                                    __nextHasNoMarginBottom={ true }
                                />
                                <TextControl
                                    label={ __( 'Password', 'appointly' ) }
                                    value={ emailData.smtp_pass }
                                    onChange={ ( val ) => setEmailData( { ...emailData, smtp_pass: val } ) }
                                    type="password"
                                    help={ __( 'For Gmail/iCloud: use an App Password, not your regular password.', 'appointly' ) }
                                    __next40pxDefaultSize={ true }
                                    __nextHasNoMarginBottom={ true }
                                />
                                <SmtpTestButton emailData={ emailData } />
                            </>
                        ) }
                    </div>
                </WizardStep>
            ) }

            { /* Step 3: Embed Calendar + Finish */ }
            { step === 3 && (
                <WizardStep
                    step={ 3 }
                    totalSteps={ TOTAL_STEPS }
                    title={ __( 'Add Your Booking Calendar', 'appointly' ) }
                    onNext={ handleFinish }
                    onBack={ () => { setError( null ); setStep( 2 ); } }
                    nextLabel={ __( 'Finish Setup', 'appointly' ) }
                    loading={ saving }
                >
                    <div style={ { textAlign: 'center', padding: '16px 0' } }>
                        <div style={ { marginBottom: '24px' } }>
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="40"
                                height="40"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="#A855F7"
                                strokeWidth="1.5"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                            >
                                <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" />
                            </svg>
                        </div>
                        <p style={ { fontSize: '15px', color: '#334155', marginBottom: '16px' } }>
                            { __( 'Paste this shortcode onto any page or post to embed your booking calendar:', 'appointly' ) }
                        </p>
                        <code style={ {
                            display: 'inline-block',
                            padding: '12px 18px',
                            background: '#F5F0FF',
                            border: '1px solid #E8E0F0',
                            borderRadius: '8px',
                            fontSize: '15px',
                            color: '#1A0E2E',
                            fontFamily: 'DM Mono, JetBrains Mono, monospace',
                        } }>
                            [appointly_calendar]
                        </code>
                        <p style={ { fontSize: '13px', color: '#64748b', marginTop: '20px' } }>
                            { __( 'Or add the "Booking Calendar" block in the Gutenberg editor.', 'appointly' ) }
                        </p>
                    </div>
                </WizardStep>
            ) }
        </div>
    );
}
