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

export default function OfferModal( { booking, onClose, onSuccess } ) {
    const [ price, setPrice ]                   = useState( '' );
    const [ adminNote, setAdminNote ]           = useState( '' );
    const [ loading, setLoading ]               = useState( false );
    const [ error, setError ]                   = useState( null );

    // Calculate addon subtotal from booking addon_selections
    const addonSubtotal = useMemo( () => {
        const selections = booking?.addon_selections || booking?.addons_selected || [];
        if ( ! Array.isArray( selections ) || selections.length === 0 ) return 0;
        return selections.reduce( ( sum, addon ) => {
            const addonPrice = parseFloat( addon.price ) || 0;
            const qty = parseInt( addon.quantity, 10 ) || 1;
            return sum + ( addonPrice * qty );
        }, 0 );
    }, [ booking ] );

    // Base price from service
    const basePrice = parseFloat( booking?.base_price || booking?.service_base_price ) || 0;

    // Grand total = entered price (or base_price if no price entered) + addon subtotal
    const enteredPrice = parseFloat( price ) || 0;
    const grandTotal = enteredPrice + addonSubtotal;

    const handleSubmit = async () => {
        // Negative prices are the only hard-fail case. Empty string → no
        // price (send the offer without a price), and 0 is a valid free
        // offer.
        const trimmed = price === '' || price === null || price === undefined
            ? ''
            : String( price ).trim();
        let parsedPrice = null;
        if ( trimmed !== '' ) {
            parsedPrice = parseFloat( trimmed );
            if ( Number.isNaN( parsedPrice ) || parsedPrice < 0 ) {
                setError( __( 'Please enter a valid price (0 or higher), or leave the field empty to send an offer without a price.', 'appointly' ) );
                return;
            }
        }

        setLoading( true );
        setError( null );

        try {
            const payload = { admin_note: adminNote || undefined };
            if ( parsedPrice !== null ) {
                payload.price = parsedPrice;
            }
            await api.sendOffer( booking.id, payload );
            onSuccess();
        } catch ( err ) {
            setError(
                err?.message || __( 'Failed to send offer. Please try again.', 'appointly' )
            );
        } finally {
            setLoading( false );
        }
    };

    return (
        <Modal
            title={ __( 'Send Offer', 'appointly' ) }
            onRequestClose={ onClose }
            className="appointly-offer-modal"
        >
            <div className="appointly-offer-modal__summary">
                <p>
                    <strong>{ __( 'Customer:', 'appointly' ) }</strong>{ ' ' }
                    { booking.customer_name }
                </p>
                <p>
                    <strong>{ __( 'Service:', 'appointly' ) }</strong>{ ' ' }
                    { booking.service_name }
                </p>
                <p>
                    <strong>{ __( 'Date:', 'appointly' ) }</strong>{ ' ' }
                    { booking.booking_date }
                </p>
            </div>

            { /* Pricing breakdown */ }
            <div className="appointly-offer-modal__pricing">
                { basePrice > 0 && (
                    <div className="appointly-offer-modal__pricing-row">
                        <span>{ __( 'Base Price:', 'appointly' ) }</span>
                        <span>{ basePrice.toFixed( 2 ) }&euro;</span>
                    </div>
                ) }
                { addonSubtotal > 0 && (
                    <div className="appointly-offer-modal__pricing-row">
                        <span>{ __( 'Addon Subtotal:', 'appointly' ) }</span>
                        <span>{ addonSubtotal.toFixed( 2 ) }&euro;</span>
                    </div>
                ) }
                { ( enteredPrice > 0 || addonSubtotal > 0 ) && (
                    <div className="appointly-offer-modal__pricing-row appointly-offer-modal__pricing-row--total">
                        <strong>{ __( 'Grand Total:', 'appointly' ) }</strong>
                        <strong>{ grandTotal.toFixed( 2 ) }&euro;</strong>
                    </div>
                ) }
            </div>

            { error && (
                <Notice status="error" isDismissible={ false } className="appointly-offer-modal__notice">
                    { error }
                </Notice>
            ) }

            <div className="appointly-offer-modal__field">
                <TextControl
                    label={ __( 'Price (\u20AC) — leave empty to send an offer without a price', 'appointly' ) }
                    type="number"
                    step="0.01"
                    min="0"
                    value={ price }
                    onChange={ setPrice }
                    placeholder={ basePrice > 0 ? String( basePrice ) : '0.00' }
                    __next40pxDefaultSize={ true }
                    __nextHasNoMarginBottom={ true }
                />
            </div>

            <div className="appointly-offer-modal__field">
                <TextareaControl
                    label={ __( 'Admin Note (optional)', 'appointly' ) }
                    value={ adminNote }
                    onChange={ setAdminNote }
                    rows={ 3 }
                    placeholder={ __( 'Internal note, not visible to customer...', 'appointly' ) }
                    __nextHasNoMarginBottom={ true }
                />
            </div>

            <div className="appointly-offer-modal__actions">
                <Button variant="secondary" onClick={ onClose } disabled={ loading }>
                    { __( 'Cancel', 'appointly' ) }
                </Button>
                <Button variant="primary" onClick={ handleSubmit } disabled={ loading }>
                    { loading && <Spinner /> }
                    { __( 'Send Offer', 'appointly' ) }
                </Button>
            </div>
        </Modal>
    );
}
