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

interface WorkOrder {
    id: number;
    order_number: string;
    client: { id: number; name: string };
    asset?: { id: number; asset_tag: string; type: string; brand?: string; model?: string };
    issue_description: string;
    status: string;
    priority: string;
    received_at: string;
    due_at?: string;
    estimated_cost?: number;
    final_cost?: number;
    assigned_to?: { id: number; name: string };
}

const statusConfig: Record<string, { label: string; class: string; emoji: string }> = {
    received: { label: 'Recibida', class: 'badge-default', emoji: '📥' },
    diagnosing: { label: 'Diagnosticando', class: 'badge-info', emoji: '🔍' },
    waiting_parts: { label: 'Esperando Partes', class: 'badge-warning', emoji: '⏳' },
    repairing: { label: 'Reparando', class: 'badge-primary', emoji: '🔧' },
    ready: { label: 'Lista', class: 'badge-success', emoji: '✅' },
    delivered: { label: 'Entregada', class: 'badge-success', emoji: '🎉' },
    cancelled: { label: 'Cancelada', class: 'badge-danger', emoji: '❌' },
};

const priorityConfig: Record<string, { label: string; class: string; emoji: string }> = {
    low: { label: 'Baja', class: 'badge-default', emoji: '🔵' },
    medium: { label: 'Media', class: 'badge-info', emoji: '🟡' },
    high: { label: 'Alta', class: 'badge-warning', emoji: '🟠' },
    urgent: { label: 'Urgente', class: 'badge-danger', emoji: '🔴' },
};

export default function WorkshopWorkOrders() {
    const [searchParams] = useSearchParams();
    const [workOrders, setWorkOrders] = useState<WorkOrder[]>([]);
    const [loading, setLoading] = useState(true);
    const [showNewModal, setShowNewModal] = useState(false);
    const [filter, setFilter] = useState({
        status: searchParams.get('status') || '',
        client_id: searchParams.get('client_id') || '',
    });

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

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

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

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

    return (
        <div className="page">
            <PageHeader
                title="Órdenes de Trabajo"
                subtitle="Gestión de reparaciones y mantenimiento"
                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="received">Recibidas</option>
                            <option value="diagnosing">Diagnosticando</option>
                            <option value="waiting_parts">Esperando Partes</option>
                            <option value="repairing">Reparando</option>
                            <option value="ready">Listas</option>
                            <option value="delivered">Entregadas</option>
                        </select>
                    </div>
                    {filter.status || filter.client_id ? (
                        <button
                            className="btn btn-ghost"
                            onClick={() => setFilter({ status: '', client_id: '' })}
                            style={{ alignSelf: 'flex-end' }}
                        >
                            🔄 Limpiar Filtros
                        </button>
                    ) : null}
                </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>Equipo</th>
                                <th>Problema</th>
                                <th>Estado</th>
                                <th>Prioridad</th>
                                <th>Recibido</th>
                                <th>Costo</th>
                                <th>Técnico</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            {workOrders.length === 0 ? (
                                <tr>
                                    <td colSpan={10} style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)' }}>
                                        📋 No hay órdenes de trabajo registradas
                                    </td>
                                </tr>
                            ) : (
                                workOrders.map((order) => (
                                    <tr key={order.id}>
                                        <td>
                                            <strong style={{ color: 'var(--color-primary)' }}>
                                                {order.order_number}
                                            </strong>
                                        </td>
                                        <td>{order.client.name}</td>
                                        <td>
                                            {order.asset ? (
                                                <div>
                                                    <div style={{ fontWeight: 600 }}>{order.asset.asset_tag}</div>
                                                    <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
                                                        {order.asset.brand} {order.asset.model}
                                                    </div>
                                                </div>
                                            ) : (
                                                <span style={{ color: 'var(--text-muted)' }}>Sin equipo</span>
                                            )}
                                        </td>
                                        <td style={{ maxWidth: '200px' }}>
                                            <div style={{
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap'
                                            }}>
                                                {order.issue_description}
                                            </div>
                                        </td>
                                        <td>
                                            <span className={`badge ${statusConfig[order.status]?.class || 'badge-default'}`}>
                                                {statusConfig[order.status]?.emoji} {statusConfig[order.status]?.label || order.status}
                                            </span>
                                        </td>
                                        <td>
                                            <span className={`badge ${priorityConfig[order.priority]?.class || 'badge-default'}`}>
                                                {priorityConfig[order.priority]?.emoji} {priorityConfig[order.priority]?.label}
                                            </span>
                                        </td>
                                        <td>{new Date(order.received_at).toLocaleDateString()}</td>
                                        <td>
                                            {order.final_cost ? (
                                                <strong>${order.final_cost.toFixed(2)}</strong>
                                            ) : order.estimated_cost ? (
                                                <span style={{ color: 'var(--text-secondary)' }}>
                                                    ~${order.estimated_cost.toFixed(2)}
                                                </span>
                                            ) : (
                                                <span style={{ color: 'var(--text-muted)' }}>—</span>
                                            )}
                                        </td>
                                        <td>
                                            {order.assigned_to ? (
                                                order.assigned_to.name
                                            ) : (
                                                <span style={{ color: 'var(--text-muted)' }}>Sin asignar</span>
                                            )}
                                        </td>
                                        <td>
                                            <Link
                                                to={`/app/workshop/work-orders/${order.id}`}
                                                className="btn btn-sm btn-ghost"
                                            >
                                                👁️ Ver
                                            </Link>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

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