import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { SelectControl, TextControl } from '@wordpress/components';
import api from '../api/client';
import BookingTable from '../components/BookingTable';

const STATUS_OPTIONS = [
    { label: __( 'All Statuses', 'appointly' ), value: '' },
    { label: __( 'Pending', 'appointly' ),   value: 'pending' },
    { label: __( 'Offered', 'appointly' ),    value: 'offered' },
    { label: __( 'Confirmed', 'appointly' ),  value: 'confirmed' },
    { label: __( 'Declined', 'appointly' ),   value: 'declined' },
    { label: __( 'Cancelled', 'appointly' ),  value: 'cancelled' },
];

export default function Bookings( { navigate } ) {
    // Filters
    const [ status, setStatus ]       = useState( '' );
    const [ serviceId, setServiceId ] = useState( '' );
    const [ dateFrom, setDateFrom ]   = useState( '' );
    const [ dateTo, setDateTo ]       = useState( '' );
    const [ search, setSearch ]       = useState( '' );

    // Pagination
    const [ page, setPage ]       = useState( 1 );
    const [ perPage, setPerPage ] = useState( 25 );

    // Data
    const [ bookings, setBookings ] = useState( [] );
    const [ total, setTotal ]       = useState( 0 );
    const [ counts, setCounts ]     = useState( {} );
    const [ services, setServices ] = useState( [] );
    const [ loading, setLoading ]   = useState( true );

    // Load services for filter dropdown
    useEffect( () => {
        api.getServices()
            .then( ( data ) => {
                const list = Array.isArray( data ) ? data : ( data?.services || data?.items || [] );
                setServices( list );
            } )
            .catch( () => {} );
    }, [] );

    // Fetch bookings
    const fetchBookings = useCallback( async () => {
        setLoading( true );
        try {
            const params = { page, per_page: perPage };
            if ( status )    params.status     = status;
            if ( serviceId ) params.service_id = serviceId;
            if ( dateFrom )  params.date_from  = dateFrom;
            if ( dateTo )    params.date_to    = dateTo;
            if ( search )    params.search     = search;

            const data = await api.getBookings( params );
            setBookings( data.items || [] );
            setTotal( data.total || 0 );
            if ( data.counts ) setCounts( data.counts );
        } catch ( err ) {
            setBookings( [] );
            setTotal( 0 );
        } finally {
            setLoading( false );
        }
    }, [ status, serviceId, dateFrom, dateTo, search, page, perPage ] );

    useEffect( () => {
        fetchBookings();
    }, [ fetchBookings ] );

    // Reset page when filters change
    const handleFilterChange = ( setter ) => ( value ) => {
        setter( value );
        setPage( 1 );
    };

    // Build service options
    const serviceOptions = [
        { label: __( 'All Services', 'appointly' ), value: '' },
        ...services.map( ( s ) => ( { label: s.title || s.name || `#${ s.id }`, value: String( s.id ) } ) ),
    ];

    // Build status options with counts
    const statusOptionsWithCounts = STATUS_OPTIONS.map( ( opt ) => {
        if ( opt.value && counts[ opt.value ] !== undefined ) {
            return { ...opt, label: `${ opt.label } (${ counts[ opt.value ] })` };
        }
        return opt;
    } );

    return (
        <div className="appointly-bookings">
            <div className="appointly-bookings__header">
                <h2>{ __( 'Bookings', 'appointly' ) }</h2>
            </div>

            { /* Filter Bar */ }
            <div className="appointly-filter-bar">
                <SelectControl
                    value={ status }
                    options={ statusOptionsWithCounts }
                    onChange={ handleFilterChange( setStatus ) }
                    __nextHasNoMarginBottom
                    __next40pxDefaultSize={ true }
                />
                <SelectControl
                    value={ serviceId }
                    options={ serviceOptions }
                    onChange={ handleFilterChange( setServiceId ) }
                    __nextHasNoMarginBottom
                    __next40pxDefaultSize={ true }
                />
                <TextControl
                    type="date"
                    value={ dateFrom }
                    onChange={ handleFilterChange( setDateFrom ) }
                    placeholder={ __( 'From', 'appointly' ) }
                    __nextHasNoMarginBottom
                    __next40pxDefaultSize={ true }
                />
                <TextControl
                    type="date"
                    value={ dateTo }
                    onChange={ handleFilterChange( setDateTo ) }
                    placeholder={ __( 'To', 'appointly' ) }
                    __nextHasNoMarginBottom
                    __next40pxDefaultSize={ true }
                />
                <TextControl
                    value={ search }
                    onChange={ handleFilterChange( setSearch ) }
                    placeholder={ __( 'Search name or email...', 'appointly' ) }
                    __nextHasNoMarginBottom
                    __next40pxDefaultSize={ true }
                />
            </div>

            { /* Booking Table */ }
            <BookingTable
                bookings={ bookings }
                loading={ loading }
                page={ page }
                perPage={ perPage }
                total={ total }
                onPageChange={ setPage }
                onPerPageChange={ ( val ) => { setPerPage( val ); setPage( 1 ); } }
                onRefresh={ fetchBookings }
                navigate={ navigate }
            />
        </div>
    );
}
