/**
 * Order Detail - Complete order information view
 */

import { __ } from '@wordpress/i18n';
import { useState, useCallback, useEffect } from '@wordpress/element';
import { Button, SelectControl } from '@wordpress/components';
import { Icon, arrowLeft, trash } from '@wordpress/icons';
import { ordersApi } from '../../api/client';
import OrderTimeline from './OrderTimeline';
import NotificationLog from '../notifications/NotificationLog';
import './OrderDetail.css';

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

export default function OrderDetail({ orderId, onBack }) {
    const [order, setOrder] = useState(null);
    const [loading, setLoading] = useState(true);
    const [updating, setUpdating] = useState(false);
    const [newStatus, setNewStatus] = useState('');

    const loadOrder = useCallback(() => {
        setLoading(true);
        ordersApi.get(orderId)
        .then(result => {
            if (result.data) {
                setOrder(result.data);
                setNewStatus(result.data.status);
            }
        })
        .catch(error => {
            console.error('Load order error:', error);
        })
        .finally(() => {
            setLoading(false);
        });
    }, [orderId]);

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

    const handleStatusChange = () => {
        if (!newStatus || newStatus === order.status) return;

        setUpdating(true);
        ordersApi.updateStatus(orderId, newStatus)
        .then(result => {
            if (result.success || result.data?.valid) {
                loadOrder();
            }
        })
        .catch(error => {
            console.error('Update status error:', error);
        })
        .finally(() => {
            setUpdating(false);
        });
    };

    const handleDelete = () => {
        if (!confirm(__('Are you sure you want to delete this order?', 'formipay'))) {
            return;
        }

        ordersApi.delete([orderId])
        .then(result => {
            if (result.success) {
                onBack?.();
            }
        })
        .catch(error => {
            console.error('Delete order error:', error);
        });
    };

    if (loading) {
        return (
            <div className="formipay-order-detail">
                <div className="formipay-loading">
                    <span className="spinner is-active" />
                </div>
            </div>
        );
    }

    if (!order) {
        return (
            <div className="formipay-order-detail">
                <div className="formipay-error">
                    <p>{ __('Order not found', 'formipay') }</p>
                    <Button
                        variant="secondary"
                        onClick={onBack}
                    >
                        <Icon icon={arrowLeft} size={16} />
                        { __('Back to Orders', 'formipay') }
                    </Button>
                </div>
            </div>
        );
    }

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

    return (
        <div className="formipay-order-detail">
            <div className="formipay-detail-header">
                <Button
                    variant="secondary"
                    onClick={onBack}
                >
                    <Icon icon={arrowLeft} size={16} />
                    { __('Back', 'formipay') }
                </Button>
                <h1>
                    { __('Order', 'formipay') } #{ order.id }
                </h1>
                <div className="header-actions">
                    <Button
                        variant="secondary"
                        isDestructive
                        onClick={handleDelete}
                    >
                        <Icon icon={trash} size={16} />
                        { __('Delete', 'formipay') }
                    </Button>
                </div>
            </div>

            <div className="formipay-detail-content">
                <div className="formipay-detail-main">
                    <div className="formipay-detail-card">
                        <h3>{ __('Order Details', 'formipay') }</h3>
                        <dl className="detail-list">
                            <div>
                                <dt>{ __('Status', 'formipay') }</dt>
                                <dd>
                                    <SelectControl
                                        value={newStatus}
                                        options={STATUS_OPTIONS}
                                        onChange={setNewStatus}
                                        disabled={updating}
                                    />
                                    {newStatus !== order.status && (
                                        <Button
                                            variant="primary"
                                            size="small"
                                            onClick={handleStatusChange}
                                            disabled={updating}
                                            isBusy={updating}
                                        >
                                            { updating ? __('Updating...', 'formipay') : __('Update Status', 'formipay') }
                                        </Button>
                                    )}
                                </dd>
                            </div>
                            <div>
                                <dt>{ __('Date Created', 'formipay') }</dt>
                                <dd>{ formatDate(order.created_date) }</dd>
                            </div>
                            <div>
                                <dt>{ __('Form ID', 'formipay') }</dt>
                                <dd>{ order.form_id }</dd>
                            </div>
                            <div>
                                <dt>{ __('Payment Gateway', 'formipay') }</dt>
                                <dd>{ order.payment_gateway || '-' }</dd>
                            </div>
                        </dl>
                    </div>

                    <div className="formipay-detail-card">
                        <h3>{ __('Items', 'formipay') }</h3>
                        <table className="items-table">
                            <thead>
                                <tr>
                                    <th>{ __('Item', 'formipay') }</th>
                                    <th>{ __('Qty', 'formipay') }</th>
                                    <th>{ __('Subtotal', 'formipay') }</th>
                                </tr>
                            </thead>
                            <tbody>
                                {order.items?.map((item, index) => (
                                    <tr key={index}>
                                        <td>
                                            <strong>{ item.item }</strong>
                                            {item.description && (
                                                <small>{ item.description }</small>
                                            )}
                                        </td>
                                        <td>{ item.qty || 1 }</td>
                                        <td>{ item.subtotal_formatted || item.subtotal }</td>
                                    </tr>
                                )) || (
                                    <tr>
                                        <td colSpan="3" className="text-center">
                                            { __('No items', 'formipay') }
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colSpan="2"><strong>{ __('Total', 'formipay') }</strong></td>
                                    <td><strong>{ order.total_formatted || order.total }</strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>

                <div className="formipay-detail-sidebar">
                    <div className="formipay-detail-card">
                        <h3>{ __('Customer Information', 'formipay') }</h3>
                        {order.form_data ? (
                            <dl className="customer-info">
                                {Object.entries(order.form_data).map(([key, value]) => {
                                    if (['payment', 'payment_gateway', 'coupon_code', 'qty'].includes(key)) {
                                        return null;
                                    }
                                    return (
                                        <div key={key}>
                                            <dt>{ key.replace(/_/g, ' ') }</dt>
                                            <dd>{ value?.value || value || '-' }</dd>
                                        </div>
                                    );
                                })}
                            </dl>
                        ) : (
                            <p className="no-data">{ __('No customer data available', 'formipay') }</p>
                        )}
                    </div>

                    <OrderTimeline orderId={orderId} />

                    <NotificationLog />
                </div>
            </div>
        </div>
    );
}
