/**
 * Order List - Main orders table with filters
 */

import { __ } from '@wordpress/i18n';
import { useState, useCallback, useEffect } from '@wordpress/element';
import { SearchControl, SelectControl, Button } from '@wordpress/components';
import { Icon, list } from '@wordpress/icons';
import { ordersApi } from '../../api/client';
import OrderListItem from './OrderListItem';
import './OrderList.css';

export default function OrderList({ onSelectOrder }) {
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [total, setTotal] = useState(0);
    const [filters, setFilters] = useState({
        keyword: '',
        status: '',
        date_from: '',
        date_to: '',
    });
    const [pagination, setPagination] = useState({
        limit: 20,
        offset: 0,
    });

    const loadOrders = useCallback(() => {
        setLoading(true);
        ordersApi.list({
            keyword: filters.keyword,
            status: filters.status,
            date_from: filters.date_from,
            date_to: filters.date_to,
            limit: pagination.limit,
            offset: pagination.offset,
        })
        .then(result => {
            if (result.data) {
                setOrders(result.data.results || []);
                setTotal(result.data.total || 0);
            }
        })
        .catch(error => {
            console.error('Load orders error:', error);
        })
        .finally(() => {
            setLoading(false);
        });
    }, [filters, pagination]);

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

    const handleFilterChange = (key, value) => {
        setFilters({ ...filters, [key]: value });
        setPagination({ ...pagination, offset: 0 });
    };

    const handleSearch = (value) => {
        handleFilterChange('keyword', value);
    };

    const handlePageChange = (newOffset) => {
        setPagination({ ...pagination, offset: newOffset });
    };

    const statusOptions = {
        '': __('All Statuses', 'formipay'),
        'on-hold': __('On Hold', 'formipay'),
        'payment-confirm': __('Payment Confirmed', 'formipay'),
        'in-progress': __('In Progress', 'formipay'),
        'shipping': __('Shipping', 'formipay'),
        'completed': __('Completed', 'formipay'),
        'failed': __('Failed', 'formipay'),
        'refunded': __('Refunded', 'formipay'),
        'cancelled': __('Cancelled', 'formipay'),
    };

    const totalPages = Math.ceil(total / pagination.limit);
    const currentPage = Math.floor(pagination.offset / pagination.limit) + 1;

    return (
        <div className="formipay-order-list">
            <div className="formipay-orders-header">
                <h2>
                    <Icon icon={list} />
                    { __('Orders', 'formipay') }
                </h2>
                <span className="order-count">
                    { total } { __('orders', 'formipay') }
                </span>
            </div>

            <div className="formipay-orders-filters">
                <SearchControl
                    value={filters.keyword}
                    onChange={handleSearch}
                    placeholder={ __('Search by order ID, customer name, email...', 'formipay')}
                />

                <SelectControl
                    value={filters.status}
                    options={Object.entries(statusOptions).map(([value, label]) => ({ value, label }))}
                    onChange={(value) => handleFilterChange('status', value)}
                    label={ __('Status', 'formipay')}
                />

                <input
                    type="date"
                    value={filters.date_from}
                    onChange={(e) => handleFilterChange('date_from', e.target.value)}
                    className="formipay-date-input"
                />

                <input
                    type="date"
                    value={filters.date_to}
                    onChange={(e) => handleFilterChange('date_to', e.target.value)}
                    className="formipay-date-input"
                />

                {(filters.keyword || filters.status || filters.date_from || filters.date_to) && (
                    <Button
                        variant="secondary"
                        onClick={() => {
                            setFilters({ keyword: '', status: '', date_from: '', date_to: '' });
                            setPagination({ limit: 20, offset: 0 });
                        }}
                    >
                        { __('Clear Filters', 'formipay') }
                    </Button>
                )}
            </div>

            <div className="formipay-orders-table-wrapper">
                {loading ? (
                    <div className="formipay-loading">
                        <span className="spinner is-active" />
                    </div>
                ) : orders.length === 0 ? (
                    <div className="formipay-no-results">
                        <p>{ __('No orders found', 'formipay') }</p>
                    </div>
                ) : (
                    <>
                        <table className="formipay-orders-table wp-list-table widefat fixed striped">
                            <thead>
                                <tr>
                                    <th>{ __('ID', 'formipay') }</th>
                                    <th>{ __('Date', 'formipay') }</th>
                                    <th>{ __('Customer', 'formipay') }</th>
                                    <th>{ __('Total', 'formipay') }</th>
                                    <th>{ __('Status', 'formipay') }</th>
                                    <th>{ __('Actions', 'formipay') }</th>
                                </tr>
                            </thead>
                            <tbody>
                                {orders.map(order => (
                                    <OrderListItem
                                        key={order.id}
                                        order={order}
                                        onSelect={() => onSelectOrder?.(order.id)}
                                    />
                                ))}
                            </tbody>
                        </table>

                        {totalPages > 1 && (
                            <div className="formipay-pagination">
                                <Button
                                    variant="secondary"
                                    disabled={currentPage === 1}
                                    onClick={() => handlePageChange(pagination.offset - pagination.limit)}
                                >
                                    { __('Previous', 'formipay') }
                                </Button>
                                <span className="pagination-info">
                                    { __('Page', 'formipay') } { currentPage } { __('of', 'formipay') } { totalPages }
                                </span>
                                <Button
                                    variant="secondary"
                                    disabled={currentPage === totalPages}
                                    onClick={() => handlePageChange(pagination.offset + pagination.limit)}
                                >
                                    { __('Next', 'formipay') }
                                </Button>
                            </div>
                        )}
                    </>
                )}
            </div>
        </div>
    );
}
