import { useState, useEffect } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import axios from 'axios';
import PageHeader from '../../components/PageHeader';
import NewOrderModal from '../../components/Store/NewOrderModal';

interface Order {
    id: number;
    order_number: string;
    client: { id: number; name: string };
    status: string;
    subtotal: number;
    discount: number;
    tax: number;
    total: number;
    paid_at?: string;
    delivered_at?: string;
    created_at: string;
    items_count: number;
}

const statusConfig: Record<string, { label: string; class: string; emoji: string }> = {
    draft: { label: 'Borrador', class: 'badge-default', emoji: '📝' },
    issued: { label: 'Emitida', class: 'badge-info', emoji: '📋' },
    paid: { label: 'Pagada', class: 'badge-success', emoji: '💰' },
    delivered: { label: 'Entregada', class: 'badge-success', emoji: '✅' },
    cancelled: { label: 'Cancelada', class: 'badge-danger', emoji: '❌' },
};

export default function StoreOrders() {
    const [searchParams] = useSearchParams();
    const [orders, setOrders] = useState<Order[]>([]);
    const [loading, setLoading] = useState(true);
    const [showNewModal, setShowNewModal] = useState(false);
    const [filter, setFilter] = useState({
        status: searchParams.get('status') || '',
    });

    useEffect(() => {
        fetchOrders();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [filter.status]);

    const fetchOrders = async () => {
        try {
            setLoading(true);
            const params = new URLSearchParams();
            if (filter.status) params.append('status', filter.status);

            const res = await axios.get(`/api/store/orders?${params}`);
            setOrders(res.data.data || res.data);
        } catch (error) {
            console.error('Error fetching orders:', error);
        } finally {
            setLoading(false);
        }
    };

    if (loading) {
        return <div className="loading">Cargando...</div>;
    }

    return (
        <div className="page">
            <PageHeader
                title="🛒 Órdenes de Venta"
                subtitle="Gestión de ventas y facturación"
                actions={
                    <button className="btn btn-primary" onClick={() => setShowNewModal(true)}>
                        ➕ Nueva Orden
                    </button>
                }
            />

            {/* Filtros */}
            <div className="card" style={{ marginBottom: '1.5rem' }}>
                <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
                    <div>
                        <label className="form-label" style={{ marginBottom: '0.5rem' }}>Estado</label>
                        <select
                            className="input"
                            value={filter.status}
                            onChange={(e) => setFilter({ ...filter, status: e.target.value })}
                            style={{ minWidth: '180px' }}
                        >
                            <option value="">Todos</option>
                            <option value="draft">📝 Borrador</option>
                            <option value="issued">📋 Emitidas</option>
                            <option value="paid">💰 Pagadas</option>
                            <option value="delivered">✅ Entregadas</option>
                            <option value="cancelled">❌ Canceladas</option>
                        </select>
                    </div>
                    {filter.status && (
                        <button
                            className="btn btn-ghost"
                            onClick={() => setFilter({ status: '' })}
                            style={{ alignSelf: 'flex-end' }}
                        >
                            🔄 Limpiar Filtros
                        </button>
                    )}
                </div>
            </div>

            {/* Tabla de Órdenes */}
            <div className="card">
                <div className="table-container">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>N° Orden</th>
                                <th>Cliente</th>
                                <th>Estado</th>
                                <th>Items</th>
                                <th>Subtotal</th>
                                <th>Descuento</th>
                                <th>Total</th>
                                <th>Fecha</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            {orders.length === 0 ? (
                                <tr>
                                    <td colSpan={9} style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)' }}>
                                        🛒 No hay órdenes de venta registradas
                                    </td>
                                </tr>
                            ) : (
                                orders.map((order) => (
                                    <tr key={order.id}>
                                        <td>
                                            <strong style={{ color: 'var(--color-primary)' }}>
                                                {order.order_number}
                                            </strong>
                                        </td>
                                        <td>{order.client.name}</td>
                                        <td>
                                            <span className={`badge ${statusConfig[order.status]?.class || 'badge-default'}`}>
                                                {statusConfig[order.status]?.emoji} {statusConfig[order.status]?.label}
                                            </span>
                                        </td>
                                        <td>
                                            <span style={{
                                                padding: '0.25rem 0.5rem',
                                                background: 'var(--glass-bg)',
                                                borderRadius: '6px',
                                                fontSize: '0.875rem',
                                            }}>
                                                {order.items_count} items
                                            </span>
                                        </td>
                                        <td>${parseFloat(String(order.subtotal)).toFixed(2)}</td>
                                        <td>
                                            {order.discount > 0 ? (
                                                <span style={{ color: '#10b981' }}>-${parseFloat(String(order.discount)).toFixed(2)}</span>
                                            ) : (
                                                <span style={{ color: 'var(--text-muted)' }}>—</span>
                                            )}
                                        </td>
                                        <td>
                                            <strong style={{ fontSize: '1.05rem' }}>
                                                ${parseFloat(String(order.total)).toFixed(2)}
                                            </strong>
                                        </td>
                                        <td>
                                            <div>{new Date(order.created_at).toLocaleDateString()}</div>
                                            {order.paid_at && (
                                                <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>
                                                    Pagada: {new Date(order.paid_at).toLocaleDateString()}
                                                </div>
                                            )}
                                        </td>
                                        <td>
                                            <Link
                                                to={`/app/store/orders/${order.id}`}
                                                className="btn btn-sm btn-ghost"
                                            >
                                                👁️ Ver
                                            </Link>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Resumen */}
            {orders.length > 0 && (
                <div className="card" style={{ marginTop: '2rem' }}>
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
                        gap: '1.5rem',
                        textAlign: 'center',
                    }}>
                        <div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem' }}>
                                Total Órdenes
                            </div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 700 }}>
                                {orders.length}
                            </div>
                        </div>
                        <div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem' }}>
                                Valor Total
                            </div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 700, color: 'var(--color-primary)' }}>
                                ${orders.reduce((sum, o) => sum + parseFloat(String(o.total)), 0).toFixed(2)}
                            </div>
                        </div>
                        <div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem' }}>
                                Items Vendidos
                            </div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 700 }}>
                                {orders.reduce((sum, o) => sum + o.items_count, 0)}
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Modal Nueva Orden */}
            <NewOrderModal
                isOpen={showNewModal}
                onClose={() => setShowNewModal(false)}
                onSuccess={() => {
                    setShowNewModal(false);
                    fetchOrders();
                }}
            />
        </div>
    );
}
