/**
 * Orders Page Component
 *
 * @package Advanced_Customer_Account
 */

import { useEffect, useState, useCallback } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { format } from 'date-fns';

// Components
import { Card, LoadingSpinner, EmptyState, Pagination, Notice, StatusBadge } from '../components/Common';

/**
 * Status filter options.
 */
const statusOptions = [
    { value: '', label: __( 'All Statuses', 'advanced-customer-account' ) },
    { value: 'pending', label: __( 'Pending', 'advanced-customer-account' ) },
    { value: 'processing', label: __( 'Processing', 'advanced-customer-account' ) },
    { value: 'on-hold', label: __( 'On Hold', 'advanced-customer-account' ) },
    { value: 'completed', label: __( 'Completed', 'advanced-customer-account' ) },
    { value: 'cancelled', label: __( 'Cancelled', 'advanced-customer-account' ) },
    { value: 'refunded', label: __( 'Refunded', 'advanced-customer-account' ) },
];

/**
 * Orders page component.
 *
 * @param {Object}   props          Component props.
 * @param {Function} props.navigate Navigate function.
 * @return {JSX.Element} Orders page.
 */
const Orders = ( { navigate } ) => {
    const { fetchOrders, setFilters } = useDispatch( 'aca/orders' );
    const [ statusFilter, setStatusFilter ] = useState( '' );

    const { orders, isLoading, error, pagination, filters } = useSelect(
        ( select ) => {
            const ordersStore = select( 'aca/orders' );
            return {
                orders: ordersStore.getOrders(),
                isLoading: ordersStore.isLoading(),
                error: ordersStore.getError(),
                pagination: ordersStore.getPagination(),
                filters: ordersStore.getFilters(),
            };
        },
        []
    );

    // Fetch orders on mount and when filters change
    useEffect( () => {
        fetchOrders( {
            page: pagination.page,
            perPage: pagination.perPage,
            status: statusFilter,
        } );
    }, [ fetchOrders, statusFilter ] );

    // Format date
    const formatDate = ( dateString ) => {
        try {
            return format( new Date( dateString ), 'MMM d, yyyy' );
        } catch {
            return dateString;
        }
    };

    // Handle page change
    const handlePageChange = useCallback(
        ( page ) => {
            fetchOrders( {
                page,
                perPage: pagination.perPage,
                status: statusFilter,
            } );
        },
        [ fetchOrders, pagination.perPage, statusFilter ]
    );

    // Handle status filter change
    const handleStatusChange = ( event ) => {
        setStatusFilter( event.target.value );
        setFilters( { status: event.target.value } );
    };

    // Handle view order
    const handleViewOrder = ( orderId ) => {
        navigate( 'orders', { id: orderId } );
    };

    return (
        <div className="aca-orders-page">
            { error && (
                <Notice
                    type="error"
                    message={ error }
                    className="aca-orders-page__notice"
                />
            ) }

            <Card
                title={ __( 'Your Orders', 'advanced-customer-account' ) }
                actions={
                    <div className="aca-orders-page__filters">
                        <select
                            className="aca-select"
                            value={ statusFilter }
                            onChange={ handleStatusChange }
                            aria-label={ __( 'Filter by status', 'advanced-customer-account' ) }
                        >
                            { statusOptions.map( ( option ) => (
                                <option key={ option.value } value={ option.value }>
                                    { option.label }
                                </option>
                            ) ) }
                        </select>
                    </div>
                }
                noPadding
            >
                { isLoading && orders.length === 0 ? (
                    <LoadingSpinner
                        message={ __( 'Loading orders...', 'advanced-customer-account' ) }
                        className="aca-orders-page__loading"
                    />
                ) : orders.length === 0 ? (
                    <EmptyState
                        icon="cart"
                        title={ __( 'No orders found', 'advanced-customer-account' ) }
                        message={
                            statusFilter
                                ? __( 'No orders match the selected filter.', 'advanced-customer-account' )
                                : __( 'You haven\'t placed any orders yet.', 'advanced-customer-account' )
                        }
                        action={
                            ! statusFilter && (
                                <a href={ window.acaSettings?.shopUrl || '/shop/' } className="aca-btn aca-btn--primary">
                                    { __( 'Start Shopping', 'advanced-customer-account' ) }
                                </a>
                            )
                        }
                    />
                ) : (
                    <>
                        <div className="aca-orders-table-wrapper">
                            <table className="aca-orders-table aca-orders-table--full">
                                <thead>
                                    <tr>
                                        <th>{ __( 'Order', 'advanced-customer-account' ) }</th>
                                        <th>{ __( 'Date', 'advanced-customer-account' ) }</th>
                                        <th>{ __( 'Status', 'advanced-customer-account' ) }</th>
                                        <th>{ __( 'Items', 'advanced-customer-account' ) }</th>
                                        <th>{ __( 'Total', 'advanced-customer-account' ) }</th>
                                        <th className="aca-orders-table__actions">
                                            <span className="screen-reader-text">
                                                { __( 'Actions', 'advanced-customer-account' ) }
                                            </span>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    { orders.map( ( order ) => (
                                        <tr key={ order.id }>
                                            <td>
                                                <button
                                                    type="button"
                                                    className="aca-orders-table__order-link"
                                                    onClick={ () => handleViewOrder( order.id ) }
                                                >
                                                    #{ order.number }
                                                </button>
                                            </td>
                                            <td>{ formatDate( order.date_created ) }</td>
                                            <td>
                                                <StatusBadge status={ order.status } />
                                            </td>
                                            <td>{ order.items_count || order.line_items?.length || 0 }</td>
                                            <td>
                                                <span
                                                    dangerouslySetInnerHTML={ { __html: order.total } }
                                                />
                                            </td>
                                            <td className="aca-orders-table__actions">
                                                <button
                                                    type="button"
                                                    className="aca-btn aca-btn--small aca-btn--secondary"
                                                    onClick={ () => handleViewOrder( order.id ) }
                                                >
                                                    { __( 'View', 'advanced-customer-account' ) }
                                                </button>
                                            </td>
                                        </tr>
                                    ) ) }
                                </tbody>
                            </table>
                        </div>

                        <div className="aca-orders-page__pagination">
                            <Pagination
                                page={ pagination.page }
                                totalPages={ pagination.totalPages }
                                onPageChange={ handlePageChange }
                            />
                        </div>
                    </>
                ) }
            </Card>
        </div>
    );
};

export default Orders;
