import React, { useState, useEffect, useCallback, useRef } from 'react';
import { toast } from 'react-toastify';
import warehouseService from '../services/warehouseService';
import assetService from '../services/assetService';
import userService from '../services/userService';

const ASSET_TYPES = ['Notebook', 'Monitor', 'Headset', 'Other', 'Maschine', 'Werkzeug', 'Sonstiges'];
const STATUS_LABELS = { verfuegbar: 'Verfügbar', zugewiesen: 'In Verwendung', inaktiv: 'Inaktiv', beschaedigt: 'Defekt', bestellt: 'Bestellt' };
const STATUS_COLORS = { verfuegbar: '#34d399', zugewiesen: '#60a5fa', inaktiv: '#6b7280', beschaedigt: '#ef4444', bestellt: '#f59e0b' };
const timeAgo = (iso) => { if (!iso) return '–'; const m = Math.floor((Date.now() - new Date(iso)) / 60000); if (m < 1) return 'gerade'; if (m < 60) return `vor ${m} Min.`; const h = Math.floor(m / 60); if (h < 24) return `vor ${h} Std.`; return `vor ${Math.floor(h / 24)} Tag(en)`; };

// ─── QR Scanner Modal ────────────────────────────────────────────────────────
const QrScannerModal = ({ onClose, onResult }) => {
    const videoRef = useRef(null);
    const [error, setError] = useState('');
    const scannerRef = useRef(null);

    useEffect(() => {
        let html5QrCode;
        import('html5-qrcode').then(({ Html5Qrcode }) => {
            html5QrCode = new Html5Qrcode('qr-reader');
            scannerRef.current = html5QrCode;
            html5QrCode.start(
                { facingMode: 'environment' },
                { fps: 10, qrbox: { width: 250, height: 250 } },
                (decodedText) => {
                    html5QrCode.stop().catch(() => {});
                    onResult(decodedText);
                    onClose();
                },
                () => {}
            ).catch(err => setError('Kamera konnte nicht gestartet werden: ' + err));
        }).catch(() => setError('QR-Scanner konnte nicht geladen werden.'));

        return () => {
            if (scannerRef.current) {
                scannerRef.current.stop().catch(() => {});
            }
        };
    }, [onClose, onResult]);

    return (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ background: 'var(--bg-secondary)', borderRadius: 14, padding: 24, width: 360, maxWidth: '95vw' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                    <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>QR-Code scannen</h3>
                    <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: 'var(--text-muted)' }}>×</button>
                </div>
                {error ? (
                    <div style={{ color: '#ef4444', fontSize: 13, padding: 12 }}>{error}</div>
                ) : (
                    <div id="qr-reader" style={{ width: '100%', borderRadius: 8, overflow: 'hidden' }} />
                )}
                <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-muted)', textAlign: 'center' }}>Kamera auf QR-Code richten</div>
            </div>
        </div>
    );
};

// ─── Movement Dialog ──────────────────────────────────────────────────────────
const MovementDialog = ({ asset, locations, users, onClose, onSave }) => {
    const [form, setForm] = useState({ type: 'out', to_location_id: '', assigned_user_id: '', ticket_id: '', reason: '', notes: '', new_status: '' });
    const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            await warehouseService.createMovement({ asset_id: asset.id, ...form });
            toast.success('Bewegung gespeichert');
            onSave();
            onClose();
        } catch { toast.error('Fehler beim Speichern'); }
    };

    const inp = { padding: '7px 10px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'var(--text-primary)', fontSize: 13, width: '100%', boxSizing: 'border-box' };
    const lbl = { fontSize: 12, color: 'var(--text-muted)', marginBottom: 4, display: 'block' };

    return (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 900, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ background: 'var(--bg-secondary)', borderRadius: 14, padding: 24, width: 440, maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
                    <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Ein-/Ausbuchen: {asset.name}</h3>
                    <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: 'var(--text-muted)' }}>×</button>
                </div>
                <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    <div>
                        <label style={lbl}>Typ *</label>
                        <select style={inp} value={form.type} onChange={e => set('type', e.target.value)}>
                            <option value="out">Ausbuchen (Ausgabe)</option>
                            <option value="in">Einbuchen (Rücknahme)</option>
                            <option value="transfer">Umlagern</option>
                            <option value="status_change">Statusänderung</option>
                        </select>
                    </div>
                    <div>
                        <label style={lbl}>Ziel-Lagerort</label>
                        <select style={inp} value={form.to_location_id} onChange={e => set('to_location_id', e.target.value)}>
                            <option value="">— kein Lagerort —</option>
                            {locations.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
                        </select>
                    </div>
                    {(form.type === 'out') && (
                        <div>
                            <label style={lbl}>Mitarbeiter</label>
                            <select style={inp} value={form.assigned_user_id} onChange={e => set('assigned_user_id', e.target.value)}>
                                <option value="">— kein Mitarbeiter —</option>
                                {users.map(u => <option key={u.id} value={u.id}>{u.first_name} {u.last_name}</option>)}
                            </select>
                        </div>
                    )}
                    <div>
                        <label style={lbl}>Ticket-ID (optional)</label>
                        <input style={inp} type="number" placeholder="z.B. 1023" value={form.ticket_id} onChange={e => set('ticket_id', e.target.value)} />
                    </div>
                    <div>
                        <label style={lbl}>Neuer Status (optional)</label>
                        <select style={inp} value={form.new_status} onChange={e => set('new_status', e.target.value)}>
                            <option value="">— unverändert —</option>
                            {Object.entries(STATUS_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                        </select>
                    </div>
                    <div>
                        <label style={lbl}>Grund *</label>
                        <input style={inp} required placeholder="z.B. Ausgabe an Mitarbeiter" value={form.reason} onChange={e => set('reason', e.target.value)} />
                    </div>
                    <div>
                        <label style={lbl}>Notizen</label>
                        <textarea style={{ ...inp, resize: 'vertical', minHeight: 60 }} value={form.notes} onChange={e => set('notes', e.target.value)} />
                    </div>
                    <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 6 }}>
                        <button type="button" onClick={onClose} style={{ padding: '8px 18px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>Abbrechen</button>
                        <button type="submit" style={{ padding: '8px 18px', borderRadius: 8, border: 'none', background: 'var(--accent)', color: '#fff', fontWeight: 700, cursor: 'pointer' }}>Speichern</button>
                    </div>
                </form>
            </div>
        </div>
    );
};

// ─── Main Page ────────────────────────────────────────────────────────────────
const WarehousePage = () => {
    const [tab, setTab]               = useState('overview');
    const [summary, setSummary]       = useState(null);
    const [locations, setLocations]   = useState([]);
    const [movements, setMovements]   = useState([]);
    const [thresholds, setThresholds] = useState([]);
    const [orders, setOrders]         = useState([]);
    const [assets, setAssets]         = useState([]);
    const [users, setUsers]           = useState([]);
    const [loading, setLoading]       = useState(true);
    const [showScanner, setShowScanner] = useState(false);
    const [movementAsset, setMovementAsset] = useState(null);
    const [qrAsset, setQrAsset]       = useState(null);
    const [assetSearch, setAssetSearch] = useState('');
    const [locationFilter, setLocationFilter] = useState('');
    const [statusFilter, setStatusFilter] = useState('');

    // Threshold form
    const [thresholdForm, setThresholdForm] = useState({ category: '', min_stock: 1, notify_email: '' });
    // Order form
    const [orderForm, setOrderForm] = useState({ category: '', item_name: '', quantity: 1, notes: '' });

    const load = useCallback(async () => {
        try {
            const [sum, locs, movs, thresh, ords, assetList, userList] = await Promise.all([
                warehouseService.getSummary(),
                warehouseService.getLocations(),
                warehouseService.getMovements(),
                warehouseService.getThresholds(),
                warehouseService.getOrders(),
                assetService.getAll(),
                userService.getAll(),
            ]);
            setSummary(sum);
            setLocations(locs);
            setMovements(movs);
            setThresholds(thresh);
            setOrders(ords);
            setAssets(assetList);
            setUsers(userList);
        } catch { toast.error('Fehler beim Laden'); }
        finally { setLoading(false); }
    }, []);

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

    const handleQrResult = (text) => {
        // Extract asset ID from URL: /assets?scan=42
        const m = text.match(/[?&]scan=(\d+)/);
        if (m) {
            const found = assets.find(a => a.id === parseInt(m[1]));
            if (found) { setMovementAsset(found); return; }
        }
        toast.error('Kein gültiges Asset-QR erkannt: ' + text);
    };

    const filteredAssets = assets.filter(a => {
        if (assetSearch && !`${a.name} ${a.inventory_number} ${a.serial_number}`.toLowerCase().includes(assetSearch.toLowerCase())) return false;
        if (statusFilter && a.status !== statusFilter) return false;
        if (locationFilter && String(a.location_id) !== locationFilter) return false;
        return true;
    });

    // ── Styles ──
    const card = { background: 'var(--bg-secondary)', border: '1px solid var(--border-color)', borderRadius: 10, padding: '14px 18px' };
    const inp = { padding: '7px 10px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'var(--text-primary)', fontSize: 13 };
    const btn = (color = 'var(--accent)') => ({ padding: '7px 16px', borderRadius: 8, border: 'none', background: color, color: '#fff', fontSize: 13, cursor: 'pointer', fontWeight: 600 });
    const tabBtn = (id) => ({ padding: '10px 20px', border: 'none', background: 'none', cursor: 'pointer', fontSize: 13, fontWeight: tab === id ? 700 : 400, color: tab === id ? 'var(--accent)' : 'var(--text-muted)', borderBottom: tab === id ? '2px solid var(--accent)' : '2px solid transparent', marginBottom: -1 });

    if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>Laden…</div>;

    return (
        <div style={{ padding: 24 }}>
            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
                <div>
                    <h1 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>📦 Lager</h1>
                    <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>Lager- und Inventarverwaltung</div>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                    <button style={{ ...btn('#6b7280') }} onClick={() => setShowScanner(true)}>📷 QR scannen</button>
                    <button style={btn()} onClick={load}>↻ Aktualisieren</button>
                </div>
            </div>

            {/* Violation banner */}
            {summary?.violations?.length > 0 && (
                <div style={{ marginBottom: 18, padding: '12px 18px', borderRadius: 10, background: '#ef444420', border: '1px solid #ef444444', display: 'flex', alignItems: 'center', gap: 12 }}>
                    <span style={{ fontSize: 18 }}>⚠️</span>
                    <div>
                        <strong style={{ color: '#ef4444' }}>Mindestbestand unterschritten!</strong>
                        <span style={{ color: 'var(--text-secondary)', fontSize: 13, marginLeft: 8 }}>
                            {summary.violations.map(v => `${v.category}: ${v.current_stock}/${v.min_stock}`).join(' · ')}
                        </span>
                    </div>
                    <button onClick={() => setTab('thresholds')} style={{ marginLeft: 'auto', ...btn('#ef4444'), padding: '5px 12px', fontSize: 12 }}>Anzeigen →</button>
                </div>
            )}

            {/* Tab bar */}
            <div style={{ display: 'flex', borderBottom: '1px solid var(--border-color)', marginBottom: 20 }}>
                {[['overview','Übersicht'],['assets','Assets'],['movements','Bewegungen'],['thresholds','Mindestbestand'],['orders','Bestellungen']].map(([id, label]) => (
                    <button key={id} style={tabBtn(id)} onClick={() => setTab(id)}>{label}</button>
                ))}
            </div>

            {/* ── ÜBERSICHT ── */}
            {tab === 'overview' && summary && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                    {/* Stats row */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12 }}>
                        {summary.stockByLocation.map(loc => (
                            <div key={loc.location} style={{ ...card, textAlign: 'center' }}>
                                <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--accent)' }}>{loc.count}</div>
                                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>📍 {loc.location}</div>
                            </div>
                        ))}
                        <div style={{ ...card, textAlign: 'center', borderColor: '#f59e0b44' }}>
                            <div style={{ fontSize: 22, fontWeight: 700, color: '#f59e0b' }}>{summary.openOrders}</div>
                            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>🛒 Offene Bestellungen</div>
                        </div>
                        <div style={{ ...card, textAlign: 'center', borderColor: summary.violations.length > 0 ? '#ef444455' : 'var(--border-color)' }}>
                            <div style={{ fontSize: 22, fontWeight: 700, color: summary.violations.length > 0 ? '#ef4444' : '#34d399' }}>{summary.violations.length}</div>
                            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>⚠️ Mindestbestand-Warnings</div>
                        </div>
                    </div>

                    {/* Stock by category */}
                    <div style={card}>
                        <div style={{ fontWeight: 700, marginBottom: 12 }}>Bestand nach Kategorie</div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                            {ASSET_TYPES.map(type => {
                                const rows = summary.stockByCategory.filter(r => r.category === type);
                                if (rows.length === 0) return null;
                                const total = rows.reduce((s, r) => s + r.count, 0);
                                return (
                                    <div key={type} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', borderBottom: '1px solid var(--border-color)' }}>
                                        <span style={{ minWidth: 100, fontSize: 13, fontWeight: 600 }}>{type}</span>
                                        <span style={{ fontSize: 13, color: 'var(--text-muted)', marginRight: 4 }}>Gesamt: {total}</span>
                                        {rows.map(r => (
                                            <span key={r.status} style={{ fontSize: 11, padding: '2px 8px', borderRadius: 5, background: (STATUS_COLORS[r.status] || '#888') + '22', color: STATUS_COLORS[r.status] || '#888', border: `1px solid ${STATUS_COLORS[r.status] || '#888'}44` }}>
                                                {STATUS_LABELS[r.status] || r.status}: {r.count}
                                            </span>
                                        ))}
                                    </div>
                                );
                            })}
                        </div>
                    </div>

                    {/* Recent movements */}
                    <div style={card}>
                        <div style={{ fontWeight: 700, marginBottom: 12 }}>Letzte Bewegungen</div>
                        {summary.recentMovements.length === 0 ? (
                            <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>Noch keine Bewegungen</div>
                        ) : (
                            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                                {summary.recentMovements.map(m => (
                                    <div key={m.id} style={{ display: 'flex', gap: 12, alignItems: 'center', fontSize: 13, padding: '5px 0', borderBottom: '1px solid var(--border-color)' }}>
                                        <span style={{ color: 'var(--text-muted)', minWidth: 90 }}>{timeAgo(m.created_at)}</span>
                                        <span style={{ fontWeight: 600 }}>{m.asset_name}</span>
                                        <span style={{ color: 'var(--text-muted)' }}>{m.type === 'in' ? '⬇ Eingebucht' : m.type === 'out' ? '⬆ Ausgebucht' : m.type === 'transfer' ? '↔ Umgelagert' : '✏ Status'}</span>
                                        {m.to_location_name && <span>→ {m.to_location_name}</span>}
                                        <span style={{ marginLeft: 'auto', color: 'var(--text-muted)' }}>{m.performed_by_name}</span>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* ── ASSETS ── */}
            {tab === 'assets' && (
                <div>
                    <div style={{ display: 'flex', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
                        <input style={{ ...inp, flex: 1, minWidth: 200 }} placeholder="Suche (Name, Inv-Nr, Seriennr.)" value={assetSearch} onChange={e => setAssetSearch(e.target.value)} />
                        <select style={inp} value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
                            <option value="">Alle Status</option>
                            {Object.entries(STATUS_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                        </select>
                        <select style={inp} value={locationFilter} onChange={e => setLocationFilter(e.target.value)}>
                            <option value="">Alle Lagerorte</option>
                            {locations.map(l => <option key={l.id} value={String(l.id)}>{l.name}</option>)}
                        </select>
                    </div>

                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                        {filteredAssets.length === 0 && <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)' }}>Keine Assets gefunden</div>}
                        {filteredAssets.map(asset => {
                            const loc = locations.find(l => l.id === asset.location_id);
                            const sc = STATUS_COLORS[asset.status] || '#888';
                            return (
                                <div key={asset.id} style={{ ...card, display: 'flex', alignItems: 'center', gap: 14 }}>
                                    <div style={{ flex: 1 }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                                            <span style={{ fontWeight: 700, fontSize: 14 }}>{asset.name}</span>
                                            <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 5, background: sc + '22', color: sc, border: `1px solid ${sc}44` }}>{STATUS_LABELS[asset.status] || asset.status}</span>
                                            {loc && <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>📍 {loc.name}</span>}
                                        </div>
                                        <div style={{ fontSize: 12, color: 'var(--text-muted)', display: 'flex', gap: 14 }}>
                                            <span>{asset.type}</span>
                                            {asset.inventory_number && <span>#{asset.inventory_number}</span>}
                                            {asset.serial_number && <span>S/N: {asset.serial_number}</span>}
                                        </div>
                                    </div>
                                    <div style={{ display: 'flex', gap: 6 }}>
                                        <button onClick={() => setMovementAsset(asset)} style={{ ...btn(), padding: '5px 12px', fontSize: 12 }}>Ein-/Ausbuchen</button>
                                        <button onClick={() => setQrAsset(asset)} style={{ padding: '5px 10px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', fontSize: 12, cursor: 'pointer' }}>🔲 QR</button>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {/* ── BEWEGUNGEN ── */}
            {tab === 'movements' && (
                <div style={card}>
                    <div style={{ fontWeight: 700, marginBottom: 14 }}>Bewegungshistorie ({movements.length})</div>
                    {movements.length === 0 ? (
                        <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)' }}>Noch keine Bewegungen erfasst</div>
                    ) : (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                            {movements.map(m => (
                                <div key={m.id} style={{ display: 'grid', gridTemplateColumns: '100px 1fr 1fr 1fr 100px', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--border-color)', fontSize: 13, alignItems: 'center' }}>
                                    <span style={{ color: 'var(--text-muted)', fontSize: 11 }}>{timeAgo(m.created_at)}</span>
                                    <span style={{ fontWeight: 600 }}>{m.asset_name} {m.inventory_number ? `(${m.inventory_number})` : ''}</span>
                                    <span style={{ color: 'var(--text-muted)' }}>
                                        {m.type === 'in' ? '⬇ Eingebucht' : m.type === 'out' ? '⬆ Ausgebucht' : m.type === 'transfer' ? '↔ Umgelagert' : '✏ Statusänderung'}
                                        {m.from_location_name && ` von ${m.from_location_name}`}
                                        {m.to_location_name && ` → ${m.to_location_name}`}
                                    </span>
                                    <span style={{ color: 'var(--text-muted)', fontSize: 12 }}>{m.reason}</span>
                                    <span style={{ color: 'var(--text-muted)', fontSize: 11 }}>{m.performed_by_name}</span>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {/* ── MINDESTBESTAND ── */}
            {tab === 'thresholds' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                    {/* Add form */}
                    <div style={card}>
                        <div style={{ fontWeight: 700, marginBottom: 12 }}>Mindestbestand konfigurieren</div>
                        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'flex-end' }}>
                            <div>
                                <label style={{ fontSize: 11, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>Kategorie</label>
                                <select style={inp} value={thresholdForm.category} onChange={e => setThresholdForm(p => ({ ...p, category: e.target.value }))}>
                                    <option value="">— wählen —</option>
                                    {ASSET_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                                </select>
                            </div>
                            <div>
                                <label style={{ fontSize: 11, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>Mindestbestand</label>
                                <input style={{ ...inp, width: 80 }} type="number" min={0} value={thresholdForm.min_stock} onChange={e => setThresholdForm(p => ({ ...p, min_stock: parseInt(e.target.value) || 0 }))} />
                            </div>
                            <div>
                                <label style={{ fontSize: 11, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>E-Mail (kommagetrennt)</label>
                                <input style={{ ...inp, width: 240 }} placeholder="admin@firma.de" value={thresholdForm.notify_email} onChange={e => setThresholdForm(p => ({ ...p, notify_email: e.target.value }))} />
                            </div>
                            <button style={btn()} onClick={async () => {
                                if (!thresholdForm.category) return toast.error('Kategorie wählen');
                                await warehouseService.upsertThreshold(thresholdForm);
                                toast.success('Gespeichert');
                                setThresholdForm({ category: '', min_stock: 1, notify_email: '' });
                                load();
                            }}>Speichern</button>
                        </div>
                    </div>

                    {/* Violations */}
                    {summary?.violations?.length > 0 && (
                        <div style={{ ...card, borderColor: '#ef444444' }}>
                            <div style={{ fontWeight: 700, marginBottom: 10, color: '#ef4444' }}>⚠️ Unterschrittene Mindestbestände</div>
                            {summary.violations.map(v => (
                                <div key={v.category} style={{ display: 'flex', gap: 12, padding: '6px 0', borderBottom: '1px solid var(--border-color)', fontSize: 13 }}>
                                    <span style={{ fontWeight: 600, minWidth: 120 }}>{v.category}</span>
                                    <span style={{ color: '#ef4444' }}>Bestand: {v.current_stock}</span>
                                    <span style={{ color: 'var(--text-muted)' }}>Minimum: {v.min_stock}</span>
                                    <button onClick={async () => {
                                        await warehouseService.createOrder({ category: v.category, item_name: v.category, quantity: v.min_stock - v.current_stock });
                                        toast.success('Bestellvorschlag erstellt');
                                        load();
                                    }} style={{ marginLeft: 'auto', ...btn('#f59e0b'), padding: '3px 10px', fontSize: 11 }}>🛒 Bestellvorschlag</button>
                                </div>
                            ))}
                        </div>
                    )}

                    {/* Configured thresholds */}
                    <div style={card}>
                        <div style={{ fontWeight: 700, marginBottom: 10 }}>Konfigurierte Schwellwerte</div>
                        {thresholds.length === 0 ? (
                            <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>Noch keine Schwellwerte konfiguriert</div>
                        ) : (
                            thresholds.map(t => (
                                <div key={t.category} style={{ display: 'flex', gap: 12, padding: '6px 0', borderBottom: '1px solid var(--border-color)', fontSize: 13, alignItems: 'center' }}>
                                    <span style={{ fontWeight: 600, minWidth: 120 }}>{t.category}</span>
                                    <span style={{ color: 'var(--text-muted)' }}>Min: {t.min_stock}</span>
                                    {t.notify_email && <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>📧 {t.notify_email}</span>}
                                    <button onClick={async () => { await warehouseService.deleteThreshold(t.category); toast.success('Gelöscht'); load(); }}
                                        style={{ marginLeft: 'auto', padding: '3px 8px', borderRadius: 6, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', fontSize: 11, cursor: 'pointer' }}>🗑</button>
                                </div>
                            ))
                        )}
                    </div>
                </div>
            )}

            {/* ── BESTELLUNGEN ── */}
            {tab === 'orders' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                    {/* Add order */}
                    <div style={card}>
                        <div style={{ fontWeight: 700, marginBottom: 12 }}>Neue Bestellung / Bestellvorschlag</div>
                        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'flex-end' }}>
                            <div>
                                <label style={{ fontSize: 11, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>Kategorie</label>
                                <select style={inp} value={orderForm.category} onChange={e => setOrderForm(p => ({ ...p, category: e.target.value }))}>
                                    <option value="">— wählen —</option>
                                    {ASSET_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                                </select>
                            </div>
                            <div>
                                <label style={{ fontSize: 11, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>Artikel</label>
                                <input style={{ ...inp, width: 200 }} placeholder="z.B. ThinkPad L15" value={orderForm.item_name} onChange={e => setOrderForm(p => ({ ...p, item_name: e.target.value }))} />
                            </div>
                            <div>
                                <label style={{ fontSize: 11, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>Menge</label>
                                <input style={{ ...inp, width: 70 }} type="number" min={1} value={orderForm.quantity} onChange={e => setOrderForm(p => ({ ...p, quantity: parseInt(e.target.value) || 1 }))} />
                            </div>
                            <div>
                                <label style={{ fontSize: 11, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>Notizen</label>
                                <input style={{ ...inp, width: 200 }} value={orderForm.notes} onChange={e => setOrderForm(p => ({ ...p, notes: e.target.value }))} />
                            </div>
                            <button style={btn()} onClick={async () => {
                                if (!orderForm.category || !orderForm.item_name) return toast.error('Kategorie und Artikel erforderlich');
                                await warehouseService.createOrder(orderForm);
                                toast.success('Bestellung erstellt');
                                setOrderForm({ category: '', item_name: '', quantity: 1, notes: '' });
                                load();
                            }}>Erstellen</button>
                        </div>
                    </div>

                    {/* Order list */}
                    {['offen', 'bestellt', 'erledigt'].map(status => {
                        const statusOrders = orders.filter(o => o.status === status);
                        if (statusOrders.length === 0) return null;
                        const statusColor = status === 'offen' ? '#f59e0b' : status === 'bestellt' ? '#60a5fa' : '#34d399';
                        const statusLabel = status === 'offen' ? 'Offen' : status === 'bestellt' ? 'Bestellt' : 'Erledigt';
                        return (
                            <div key={status} style={{ ...card, borderColor: statusColor + '44' }}>
                                <div style={{ fontWeight: 700, marginBottom: 10, color: statusColor }}>{statusLabel} ({statusOrders.length})</div>
                                {statusOrders.map(o => (
                                    <div key={o.id} style={{ display: 'flex', gap: 10, padding: '7px 0', borderBottom: '1px solid var(--border-color)', fontSize: 13, alignItems: 'center' }}>
                                        <div style={{ flex: 1 }}>
                                            <span style={{ fontWeight: 600 }}>{o.item_name}</span>
                                            <span style={{ color: 'var(--text-muted)', marginLeft: 8 }}>×{o.quantity}</span>
                                            <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--text-muted)' }}>[{o.category}]</span>
                                            {o.notes && <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--text-muted)' }}>— {o.notes}</span>}
                                            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>von {o.created_by_name} · {timeAgo(o.created_at)}</div>
                                        </div>
                                        <div style={{ display: 'flex', gap: 5 }}>
                                            {o.status === 'offen'    && <button onClick={async () => { await warehouseService.updateOrder(o.id, { status: 'bestellt' }); load(); }} style={{ ...btn('#60a5fa'), padding: '4px 10px', fontSize: 11 }}>Bestellt</button>}
                                            {o.status === 'bestellt' && <button onClick={async () => { await warehouseService.updateOrder(o.id, { status: 'erledigt' }); load(); }} style={{ ...btn('#34d399'), padding: '4px 10px', fontSize: 11 }}>Erledigt</button>}
                                            <button onClick={async () => { await warehouseService.deleteOrder(o.id); load(); }} style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', fontSize: 11, cursor: 'pointer' }}>🗑</button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        );
                    })}
                    {orders.length === 0 && <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)' }}>Keine Bestellungen vorhanden</div>}
                </div>
            )}

            {/* ── Modals ── */}
            {showScanner && <QrScannerModal onClose={() => setShowScanner(false)} onResult={handleQrResult} />}
            {movementAsset && <MovementDialog asset={movementAsset} locations={locations} users={users} onClose={() => setMovementAsset(null)} onSave={load} />}

            {/* QR Code Modal */}
            {qrAsset && (
                <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 900, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <div style={{ background: 'var(--bg-secondary)', borderRadius: 14, padding: 24, textAlign: 'center', minWidth: 280 }}>
                        <div style={{ fontWeight: 700, marginBottom: 12, fontSize: 16 }}>QR-Code: {qrAsset.name}</div>
                        <img src={warehouseService.getQrUrl(qrAsset.id)} alt="QR Code" style={{ width: 200, height: 200, display: 'block', margin: '0 auto 12px' }} />
                        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 16 }}>{qrAsset.inventory_number || `ID: ${qrAsset.id}`}</div>
                        <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
                            <a href={warehouseService.getQrUrl(qrAsset.id)} download={`qr-${qrAsset.inventory_number || qrAsset.id}.svg`}
                               style={{ ...btn(), textDecoration: 'none', display: 'inline-block', padding: '7px 16px' }}>⬇ Herunterladen</a>
                            <button onClick={() => setQrAsset(null)} style={{ padding: '7px 16px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>Schließen</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default WarehousePage;
