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

const AssetAssignModal = ({ asset, onClose, onAssigned }) => {
    const [users, setUsers] = useState([]);
    const [selectedUser, setSelectedUser] = useState(null);
    const [search, setSearch] = useState('');
    const [dropOpen, setDropOpen] = useState(false);
    const [dropPos, setDropPos] = useState({ top: 0, left: 0, width: 300 });
    const [notes, setNotes] = useState('');
    const [loading, setLoading] = useState(false);
    const [loadingUsers, setLoadingUsers] = useState(true);
    const inputRef = useRef(null);

    const updateDropPos = () => {
        if (inputRef.current) {
            const r = inputRef.current.getBoundingClientRect();
            setDropPos({ top: r.bottom + 2, left: r.left, width: r.width });
        }
    };

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

    const loadUsers = async () => {
        try {
            const data = await userService.getAll();
            const sorted = data
                .filter(u => u.is_active)
                .sort((a, b) => {
                    const nameA = `${a.last_name} ${a.first_name}`.trim().toLowerCase();
                    const nameB = `${b.last_name} ${b.first_name}`.trim().toLowerCase();
                    return nameA.localeCompare(nameB, 'de');
                });
            setUsers(sorted);
        } catch {
            toast.error('Fehler beim Laden der Benutzer');
        } finally {
            setLoadingUsers(false);
        }
    };

    const filtered = users.filter(u => {
        const q = search.toLowerCase();
        return !q
            || u.username?.toLowerCase().includes(q)
            || u.first_name?.toLowerCase().includes(q)
            || u.last_name?.toLowerCase().includes(q)
            || `${u.first_name} ${u.last_name}`.toLowerCase().includes(q);
    });

    const handleSelect = (user) => {
        setSelectedUser(user);
        setSearch('');
        setDropOpen(false);
    };

    const handleClear = () => {
        setSelectedUser(null);
        setSearch('');
        setTimeout(() => inputRef.current?.focus(), 50);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!selectedUser) {
            toast.error('Bitte einen Benutzer auswählen');
            return;
        }
        setLoading(true);
        try {
            await assetService.assign(asset.id, selectedUser.id, notes);
            toast.success('Asset erfolgreich zugewiesen');
            onAssigned();
        } catch (error) {
            toast.error(error.message || 'Fehler beim Zuweisen');
        } finally {
            setLoading(false);
        }
    };

    const displayName = (u) =>
        u.first_name || u.last_name
            ? `${u.first_name || ''} ${u.last_name || ''}`.trim()
            : u.username;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h2 className="modal-title">Asset zuweisen</h2>
                    <button className="modal-close" onClick={onClose}>×</button>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label className="form-label">Asset</label>
                        <input
                            type="text"
                            className="form-input"
                            value={`${asset.name} (${asset.serial_number})`}
                            disabled
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Benutzer auswählen *</label>
                        {loadingUsers ? (
                            <p style={{ color: 'var(--text-muted)', fontSize: '0.875rem' }}>Lade Benutzer…</p>
                        ) : selectedUser ? (
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', border: '1px solid var(--border-color)', borderRadius: 6, background: 'var(--input-bg, var(--card-bg))' }}>
                                <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: '0.875rem', flexShrink: 0 }}>
                                    {displayName(selectedUser).charAt(0).toUpperCase()}
                                </div>
                                <div style={{ flex: 1, minWidth: 0 }}>
                                    <div style={{ fontWeight: 600, fontSize: '0.875rem' }}>{displayName(selectedUser)}</div>
                                    <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>@{selectedUser.username}</div>
                                </div>
                                <button type="button" onClick={handleClear} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: '1rem', padding: '2px 6px' }}>✕</button>
                            </div>
                        ) : (
                            <div style={{ position: 'relative' }}>
                                <input
                                    ref={inputRef}
                                    className="form-input"
                                    style={{ width: '100%' }}
                                    placeholder="Name oder Benutzername suchen…"
                                    value={search}
                                    onChange={e => { setSearch(e.target.value); updateDropPos(); setDropOpen(true); }}
                                    onFocus={() => { requestAnimationFrame(() => { updateDropPos(); setDropOpen(true); }); }}
                                    onBlur={() => setTimeout(() => setDropOpen(false), 150)}
                                    autoFocus
                                />
                                {dropOpen && (
                                    <div style={{ position: 'fixed', top: dropPos.top, left: dropPos.left, width: dropPos.width, zIndex: 9999, background: 'var(--card-bg, #1e1e2e)', border: '1px solid var(--border-color)', borderRadius: 6, boxShadow: '0 8px 24px rgba(0,0,0,0.5)', maxHeight: 240, overflowY: 'auto' }}>
                                        {filtered.length === 0 ? (
                                            <div style={{ padding: '10px 12px', color: 'var(--text-muted)', fontSize: '0.85rem' }}>Kein Benutzer gefunden</div>
                                        ) : filtered.map(u => (
                                            <div
                                                key={u.id}
                                                onMouseDown={() => handleSelect(u)}
                                                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', cursor: 'pointer' }}
                                                onMouseEnter={e => e.currentTarget.style.background = 'var(--hover-bg, rgba(255,255,255,0.05))'}
                                                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                                            >
                                                <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: '0.75rem', flexShrink: 0 }}>
                                                    {displayName(u).charAt(0).toUpperCase()}
                                                </div>
                                                <div>
                                                    <div style={{ fontWeight: 600, fontSize: '0.85rem' }}>{displayName(u)}</div>
                                                    <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>@{u.username}</div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                        )}
                    </div>

                    <div className="form-group">
                        <label className="form-label">Notizen</label>
                        <textarea
                            className="form-textarea"
                            rows="3"
                            value={notes}
                            onChange={(e) => setNotes(e.target.value)}
                            placeholder="Optionale Notizen zur Zuweisung…"
                        />
                    </div>

                    <div className="card-footer">
                        <button type="button" onClick={onClose} className="btn btn-secondary" disabled={loading}>
                            Abbrechen
                        </button>
                        <button type="submit" className="btn btn-primary" disabled={loading || loadingUsers || !selectedUser}>
                            {loading ? 'Zuweisen…' : 'Zuweisen'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default AssetAssignModal;
