/**
 * Order List Item - Single row in orders table
 */

import { __ } from '@wordpress/i18n';
import { Icon, seen } from '@wordpress/icons';
import './OrderListItem.css';

const STATUS_COLORS = {
    'on-hold': '#f0ad4e',
    'payment-confirm': '#17a2b8',
    'in-progress': '#17a2b8',
    'shipping': '#6c757d',
    'completed': '#28a745',
    'failed': '#dc3545',
    'refunded': '#6c757d',
    'cancelled': '#dc3545',
};

const STATUS_LABELS = {
    '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'),
};

export default function OrderListItem({ order, onSelect }) {
    const statusColor = STATUS_COLORS[order.status] || '#6c757d';
    const statusLabel = STATUS_LABELS[order.status] || order.status;

    const formatDate = (dateString) => {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString();
    };

    const getCustomerName = (order) => {
        if (order.form_data) {
            const nameField = Object.values(order.form_data).find(
                field => field.name && field.name.includes('name')
            );
            return nameField?.value || '-';
        }
        return '-';
    };

    const customerName = getCustomerName(order);

    return (
        <tr className="formipay-order-item">
            <td>
                <strong>#{ order.id }</strong>
            </td>
            <td>
                { formatDate(order.created_date) }
            </td>
            <td>
                { customerName !== '-' ? customerName : <em>Unknown</em> }
            </td>
            <td>
                <strong>{ order.total_formatted || order.total }</strong>
            </td>
            <td>
                <span
                    className="status-badge"
                    style={{ backgroundColor: statusColor }}
                >
                    { statusLabel }
                </span>
            </td>
            <td>
                <button
                    type="button"
                    className="button button-small"
                    onClick={onSelect}
                >
                    <Icon icon={seen} size={16} />
                    { __('View', 'formipay') }
                </button>
            </td>
        </tr>
    );
}
