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

interface Asset {
    id: number;
    asset_tag: string;
    type: string;
    brand?: string;
    model?: string;
    serial_number?: string;
    purchase_date?: string;
    client: { id: number; name: string };
    notes?: string;
    created_at: string;
}

const typeConfig: Record<string, { label: string; emoji: string; color: string }> = {
    laptop: { label: 'Laptop', emoji: '💻', color: '#667eea' },
    desktop: { label: 'Desktop', emoji: '🖥️', color: '#764ba2' },
    printer: { label: 'Impresora', emoji: '🖨️', color: '#f093fb' },
    router: { label: 'Router', emoji: '📡', color: '#4facfe' },
    ups: { label: 'UPS', emoji: '🔋', color: '#43e97b' },
    server: { label: 'Servidor', emoji: '🖲️', color: '#fa709a' },
    monitor: { label: 'Monitor', emoji: '🖥️', color: '#30cfd0' },
    other: { label: 'Otro', emoji: '📦', color: '#a18cd1' },
};

export default function WorkshopAssets() {
    const [searchParams] = useSearchParams();
    const [assets, setAssets] = useState<Asset[]>([]);
    const [loading, setLoading] = useState(true);
    const [showNewModal, setShowNewModal] = useState(false);
    const [filter, setFilter] = useState({
        type: searchParams.get('type') || '',
        client_id: searchParams.get('client_id') || '',
    });

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

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

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

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

    return (
        <div className="page">
            <PageHeader
                title="Equipos del Cliente"
                subtitle="Inventario de activos físicos registrados"
                actions={
                    <button className="btn btn-primary" onClick={() => setShowNewModal(true)}>
                        ➕ Registrar Equipo
                    </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' }}>Tipo de Equipo</label>
                        <select
                            className="input"
                            value={filter.type}
                            onChange={(e) => setFilter({ ...filter, type: e.target.value })}
                            style={{ minWidth: '180px' }}
                        >
                            <option value="">Todos</option>
                            <option value="laptop">💻 Laptop</option>
                            <option value="desktop">🖥️ Desktop</option>
                            <option value="printer">🖨️ Impresora</option>
                            <option value="router">📡 Router</option>
                            <option value="ups">🔋 UPS</option>
                            <option value="server">🖲️ Servidor</option>
                            <option value="monitor">🖥️ Monitor</option>
                            <option value="other">📦 Otro</option>
                        </select>
                    </div>
                    {filter.type || filter.client_id ? (
                        <button
                            className="btn btn-ghost"
                            onClick={() => setFilter({ type: '', client_id: '' })}
                            style={{ alignSelf: 'flex-end' }}
                        >
                            🔄 Limpiar Filtros
                        </button>
                    ) : null}
                </div>
            </div>

            {/* Grid de Equipos */}
            <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
                gap: '1.5rem'
            }}>
                {assets.length === 0 ? (
                    <div className="card" style={{ gridColumn: '1 / -1', padding: '3rem', textAlign: 'center' }}>
                        <div style={{ fontSize: '3rem', marginBottom: '1rem' }}>📦</div>
                        <div style={{ color: 'var(--text-secondary)', fontSize: '1.1rem' }}>
                            No hay equipos registrados
                        </div>
                    </div>
                ) : (
                    assets.map((asset) => {
                        const typeInfo = typeConfig[asset.type] || typeConfig.other;
                        return (
                            <div
                                key={asset.id}
                                className="card"
                                style={{
                                    padding: '1.5rem',
                                    borderLeft: `4px solid ${typeInfo.color}`,
                                    transition: 'transform 0.2s ease, box-shadow 0.2s ease',
                                }}
                            >
                                {/* Header */}
                                <div style={{ display: 'flex', alignItems: 'flex-start', gap: '1rem', marginBottom: '1rem' }}>
                                    <div
                                        style={{
                                            width: '48px',
                                            height: '48px',
                                            borderRadius: '12px',
                                            background: `linear-gradient(135deg, ${typeInfo.color}20, ${typeInfo.color}10)`,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            fontSize: '1.5rem',
                                        }}
                                    >
                                        {typeInfo.emoji}
                                    </div>
                                    <div style={{ flex: 1 }}>
                                        <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.25rem' }}>
                                            {typeInfo.label}
                                        </div>
                                        <div style={{ fontSize: '1.1rem', fontWeight: 700, color: 'var(--text-primary)' }}>
                                            {asset.asset_tag}
                                        </div>
                                    </div>
                                </div>

                                {/* Información del Equipo */}
                                <div style={{ marginBottom: '1rem' }}>
                                    {asset.brand && asset.model ? (
                                        <div style={{ fontSize: '0.95rem', fontWeight: 600, marginBottom: '0.5rem' }}>
                                            {asset.brand} {asset.model}
                                        </div>
                                    ) : null}
                                    {asset.serial_number ? (
                                        <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.25rem' }}>
                                            S/N: {asset.serial_number}
                                        </div>
                                    ) : null}
                                    <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>
                                        Cliente: <strong>{asset.client.name}</strong>
                                    </div>
                                    {asset.purchase_date ? (
                                        <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)', marginTop: '0.25rem' }}>
                                            Compra: {new Date(asset.purchase_date).toLocaleDateString()}
                                        </div>
                                    ) : null}
                                </div>

                                {/* Notas */}
                                {asset.notes ? (
                                    <div
                                        style={{
                                            padding: '0.75rem',
                                            background: 'var(--glass-bg)',
                                            borderRadius: '8px',
                                            fontSize: '0.85rem',
                                            color: 'var(--text-secondary)',
                                            marginBottom: '1rem',
                                            maxHeight: '60px',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis',
                                        }}
                                    >
                                        {asset.notes}
                                    </div>
                                ) : null}

                                {/* Acciones */}
                                <div style={{ display: 'flex', gap: '0.5rem', marginTop: '1rem' }}>
                                    <Link
                                        to={`/app/workshop/assets/${asset.id}`}
                                        className="btn btn-sm btn-secondary"
                                        style={{ flex: 1 }}
                                    >
                                        👁️ Ver Detalle
                                    </Link>
                                    <button
                                        className="btn btn-sm btn-primary"
                                        onClick={() => alert('Crear orden para este equipo')}
                                        style={{ flex: 1 }}
                                    >
                                        🔧 Nueva Orden
                                    </button>
                                </div>
                            </div>
                        );
                    })
                )}
            </div>

            {/* Resumen */}
            {assets.length > 0 && (
                <div className="card" style={{ marginTop: '2rem', textAlign: 'center' }}>
                    <div style={{ color: 'var(--text-secondary)' }}>
                        📦 Mostrando <strong>{assets.length}</strong> equipos registrados
                    </div>
                </div>
            )}

            {/* Modal Nuevo Equipo */}
            <NewAssetModal
                isOpen={showNewModal}
                onClose={() => setShowNewModal(false)}
                onSuccess={() => {
                    setShowNewModal(false);
                    fetchAssets();
                }}
            />
        </div>
    );
}
