import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import PageHeader from '../../components/PageHeader';

interface WorkOrderDetail {
    id: number;
    order_number: string;
    client: { id: number; name: string; email?: string; phone?: string };
    asset?: { id: number; asset_tag: string; type: string; brand?: string; model?: string };
    issue_description: string;
    intake_notes?: string;
    diagnosis_notes?: string;
    status: string;
    priority: string;
    received_at: string;
    due_at?: string;
    delivered_at?: string;
    estimated_cost?: number;
    final_cost?: number;
    assigned_to?: { id: number; name: string };
    parts: Array<{
        id: number;
        name: string;
        qty: number;
        unit_cost: number;
        total_cost: number;
        notes?: string;
    }>;
    labor: Array<{
        id: number;
        description: string;
        minutes: number;
        rate: number;
        total_cost: number;
        performed_by?: { id: number; name: string };
    }>;
}

const statusColors: Record<string, string> = {
    received: '#6366f1',
    diagnosing: '#3b82f6',
    waiting_parts: '#eab308',
    repairing: '#8b5cf6',
    ready: '#10b981',
    delivered: '#22c55e',
    cancelled: '#ef4444',
};

export default function WorkOrderDetail() {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const [order, setOrder] = useState<WorkOrderDetail | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (id) {
            fetchOrder();
        }
    }, [id]);

    const fetchOrder = async () => {
        try {
            setLoading(true);
            const res = await axios.get(`/api/workshop/work-orders/${id}`);
            setOrder(res.data);
        } catch (error) {
            console.error('Error fetching work order:', error);
        } finally {
            setLoading(false);
        }
    };

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

    if (!order) {
        return <div className="page"><div className="card">Orden no encontrada</div></div>;
    }

    const partsCost = order.parts.reduce((sum, p) => sum + Number(p.total_cost), 0);
    const laborCost = order.labor.reduce((sum, l) => sum + Number(l.total_cost), 0);
    const totalCost = partsCost + laborCost;

    return (
        <div className="page">
            <PageHeader
                title={`Orden ${order.order_number}`}
                subtitle={order.client.name}
                actions={
                    <div style={{ display: 'flex', gap: '0.75rem' }}>
                        <button className="btn btn-ghost" onClick={() => navigate('/app/workshop/work-orders')}>
                            ← Volver
                        </button>
                        <button className="btn btn-secondary" onClick={() => alert('Editar próximamente')}>
                            ✏️ Editar
                        </button>
                    </div>
                }
            />

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '1.5rem' }}>
                {/* Información General */}
                <div className="card">
                    <h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                        📋 Información General
                    </h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                        <div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Estado</div>
                            <div
                                style={{
                                    display: 'inline-block',
                                    marginTop: '0.25rem',
                                    padding: '0.5rem 1rem',
                                    borderRadius: '8px',
                                    background: `${statusColors[order.status]}20`,
                                    color: statusColors[order.status],
                                    fontWeight: 600,
                                }}
                            >
                                {order.status.toUpperCase()}
                            </div>
                        </div>
                        <div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Prioridad</div>
                            <div style={{ fontWeight: 600, marginTop: '0.25rem' }}>{order.priority}</div>
                        </div>
                        <div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Recibido</div>
                            <div style={{ fontWeight: 600, marginTop: '0.25rem' }}>
                                {new Date(order.received_at).toLocaleString()}
                            </div>
                        </div>
                        {order.due_at && (
                            <div>
                                <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Fecha Límite</div>
                                <div style={{ fontWeight: 600, marginTop: '0.25rem' }}>
                                    {new Date(order.due_at).toLocaleDateString()}
                                </div>
                            </div>
                        )}
                        {order.assigned_to && (
                            <div>
                                <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Técnico Asignado</div>
                                <div style={{ fontWeight: 600, marginTop: '0.25rem' }}>{order.assigned_to.name}</div>
                            </div>
                        )}
                    </div>
                </div>

                {/* Cliente y Equipo */}
                <div className="card">
                    <h3 style={{ marginBottom: '1rem' }}>👤 Cliente</h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                        <div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Nombre</div>
                            <div style={{ fontWeight: 600, marginTop: '0.25rem' }}>{order.client.name}</div>
                        </div>
                        {order.client.email && (
                            <div>
                                <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Email</div>
                                <div style={{ marginTop: '0.25rem' }}>{order.client.email}</div>
                            </div>
                        )}
                        {order.asset && (
                            <>
                                <hr style={{ margin: '0.5rem 0', border: 'none', borderTop: '1px solid var(--border-color)' }} />
                                <div>
                                    <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>Equipo</div>
                                    <div style={{ fontWeight: 600, marginTop: '0.25rem' }}>
                                        {order.asset.asset_tag}
                                    </div>
                                    {order.asset.brand && (
                                        <div style={{ fontSize: '0.875rem', marginTop: '0.25rem' }}>
                                            {order.asset.brand} {order.asset.model}
                                        </div>
                                    )}
                                </div>
                            </>
                        )}
                    </div>
                </div>

                {/* Costos */}
                <div className="card">
                    <h3 style={{ marginBottom: '1rem' }}>💰 Costos</h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                            <span style={{ color: 'var(--text-secondary)' }}>Partes</span>
                            <span style={{ fontWeight: 600 }}>${partsCost.toFixed(2)}</span>
                        </div>
                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                            <span style={{ color: 'var(--text-secondary)' }}>Mano de Obra</span>
                            <span style={{ fontWeight: 600 }}>${laborCost.toFixed(2)}</span>
                        </div>
                        <hr style={{ margin: '0.5rem 0', border: 'none', borderTop: '1px solid var(--border-color)' }} />
                        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '1.25rem' }}>
                            <span style={{ fontWeight: 700 }}>Total</span>
                            <span style={{ fontWeight: 700, color: 'var(--color-primary)' }}>
                                ${totalCost.toFixed(2)}
                            </span>
                        </div>
                        {order.estimated_cost && (
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)', textAlign: 'right' }}>
                                Estimado: ${order.estimated_cost.toFixed(2)}
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Descripción del Problema */}
            <div className="card" style={{ marginTop: '1.5rem' }}>
                <h3 style={{ marginBottom: '1rem' }}>🔍 Descripción del Problema</h3>
                <p style={{ lineHeight: 1.6 }}>{order.issue_description}</p>
                {order.intake_notes && (
                    <>
                        <hr style={{ margin: '1rem 0', border: 'none', borderTop: '1px solid var(--border-color)' }} />
                        <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem' }}>
                            Notas de Recepción
                        </div>
                        <p style={{ lineHeight: 1.6 }}>{order.intake_notes}</p>
                    </>
                )}
                {order.diagnosis_notes && (
                    <>
                        <hr style={{ margin: '1rem 0', border: 'none', borderTop: '1px solid var(--border-color)' }} />
                        <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem' }}>
                            Diagnóstico
                        </div>
                        <p style={{ lineHeight: 1.6 }}>{order.diagnosis_notes}</p>
                    </>
                )}
            </div>

            {/* Partes */}
            <div className="card" style={{ marginTop: '1.5rem' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
                    <h3>🔩 Partes Utilizadas ({order.parts.length})</h3>
                    <button className="btn btn-sm btn-primary" onClick={() => alert('Agregar parte próximamente')}>
                        ➕ Agregar Parte
                    </button>
                </div>
                {order.parts.length === 0 ? (
                    <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)' }}>
                        No se han agregado partes
                    </div>
                ) : (
                    <div className="table-container">
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>Nombre</th>
                                    <th>Cantidad</th>
                                    <th>Costo Unit.</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                {order.parts.map((part) => (
                                    <tr key={part.id}>
                                        <td>{part.name}</td>
                                        <td>{part.qty}</td>
                                        <td>${part.unit_cost.toFixed(2)}</td>
                                        <td><strong>${part.total_cost.toFixed(2)}</strong></td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            {/* Mano de Obra */}
            <div className="card" style={{ marginTop: '1.5rem' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
                    <h3>⚙️ Mano de Obra ({order.labor.length})</h3>
                    <button className="btn btn-sm btn-primary" onClick={() => alert('Agregar mano de obra próximamente')}>
                        ➕ Agregar Trabajo
                    </button>
                </div>
                {order.labor.length === 0 ? (
                    <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)' }}>
                        No se ha registrado mano de obra
                    </div>
                ) : (
                    <div className="table-container">
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>Descripción</th>
                                    <th>Tiempo</th>
                                    <th>Tasa/Hora</th>
                                    <th>Técnico</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                {order.labor.map((lab) => (
                                    <tr key={lab.id}>
                                        <td>{lab.description}</td>
                                        <td>{lab.minutes} min</td>
                                        <td>${lab.rate.toFixed(2)}</td>
                                        <td>{lab.performed_by?.name || '—'}</td>
                                        <td><strong>${lab.total_cost.toFixed(2)}</strong></td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
}
