import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import fidoKeyService from '../services/fidoKeyService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';

const API = process.env.REACT_APP_API_URL || '/api';
const authFetch = (url, opts = {}) => {
    const token = localStorage.getItem('token');
    return fetch(url, { ...opts, headers: { ...(opts.headers || {}), Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } });
};

const FidoKeysPage = () => {
    const { canModifyFidoKeys, isAdmin } = useAuth();
    const [keys, setKeys] = useState([]);
    const [filteredKeys, setFilteredKeys] = useState([]);
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [showModal, setShowModal] = useState(false);
    const [editingKey, setEditingKey] = useState(null);
    const [formData, setFormData] = useState({
        name: '',
        serial_number: '',
        status: 'aktiv',
        description: '',
        assigned_to_user_id: '',
    });

    useEffect(() => {
        loadKeys();
        authFetch(`${API}/users`)
            .then(r => r.json())
            .then(d => setUsers(d.data || d || []))
            .catch(() => {});
    }, []);

    useEffect(() => {
        filterKeys();
    }, [keys, searchTerm, statusFilter]);

    const loadKeys = async () => {
        try {
            const data = await fidoKeyService.getAll();
            setKeys(data);
        } catch (error) {
            toast.error('Fehler beim Laden der FIDO-Keys');
        } finally {
            setLoading(false);
        }
    };

    const filterKeys = () => {
        let filtered = [...keys];
        if (searchTerm) {
            filtered = filtered.filter(
                (key) =>
                    key.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    key.serial_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    (key.assigned_to_username || '').toLowerCase().includes(searchTerm.toLowerCase())
            );
        }
        if (statusFilter !== 'all') {
            filtered = filtered.filter((key) => key.status === statusFilter);
        }
        setFilteredKeys(filtered);
    };

    const handleCreate = () => {
        setEditingKey(null);
        setFormData({ name: '', serial_number: '', status: 'aktiv', description: '', assigned_to_user_id: '' });
        setShowModal(true);
    };

    const handleEdit = (key) => {
        setEditingKey(key);
        setFormData({
            name: key.name,
            serial_number: key.serial_number,
            status: key.status,
            description: key.description || '',
            assigned_to_user_id: key.assigned_to_user_id || '',
        });
        setShowModal(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const payload = {
                ...formData,
                assigned_to_user_id: formData.assigned_to_user_id ? parseInt(formData.assigned_to_user_id) : null,
            };
            if (editingKey) {
                await fidoKeyService.update(editingKey.id, payload);
                toast.success('FIDO-Key erfolgreich aktualisiert');
            } else {
                await fidoKeyService.create(payload);
                toast.success('FIDO-Key erfolgreich erstellt');
            }
            setShowModal(false);
            loadKeys();
        } catch (error) {
            toast.error(error.message || 'Fehler beim Speichern');
        }
    };

    const handleDelete = async (id) => {
        if (!window.confirm('Möchten Sie diesen FIDO-Key wirklich löschen?')) return;
        try {
            await fidoKeyService.delete(id);
            toast.success('FIDO-Key erfolgreich gelöscht');
            loadKeys();
        } catch (error) {
            toast.error(error.message || 'Fehler beim Löschen');
        }
    };

    const handleStatusToggle = async (key) => {
        const newStatus = key.status === 'aktiv' ? 'inaktiv' : 'aktiv';
        try {
            await fidoKeyService.updateStatus(key.id, newStatus);
            toast.success('Status erfolgreich geändert');
            loadKeys();
        } catch (error) {
            toast.error(error.message || 'Fehler beim Ändern des Status');
        }
    };

    const handleUnassign = async (key) => {
        try {
            await fidoKeyService.update(key.id, { ...key, assigned_to_user_id: null });
            toast.success('Zuweisung aufgehoben');
            loadKeys();
        } catch (error) {
            toast.error('Fehler beim Aufheben der Zuweisung');
        }
    };

    if (loading) {
        return (
            <div className="main-content">
                <LoadingSpinner />
            </div>
        );
    }

    return (
        <div className="main-content">
            <div className="container">
                <div className="flex justify-between items-center mb-3">
                    <h1>FIDO-Keys</h1>
                    {canModifyFidoKeys() && (
                        <button onClick={handleCreate} className="btn btn-primary">
                            + Neuer FIDO-Key
                        </button>
                    )}
                </div>

                <div className="search-container">
                    <input
                        type="text"
                        className="search-input"
                        placeholder="Suche nach Name, Seriennummer oder Benutzer..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                    <div className="filter-buttons">
                        <button className={`btn ${statusFilter === 'all' ? 'btn-primary' : 'btn-secondary'} btn-small`} onClick={() => setStatusFilter('all')}>Alle</button>
                        <button className={`btn ${statusFilter === 'aktiv' ? 'btn-success' : 'btn-secondary'} btn-small`} onClick={() => setStatusFilter('aktiv')}>Aktiv</button>
                        <button className={`btn ${statusFilter === 'inaktiv' ? 'btn-danger' : 'btn-secondary'} btn-small`} onClick={() => setStatusFilter('inaktiv')}>Inaktiv</button>
                    </div>
                </div>

                <div className="card">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Seriennummer</th>
                                <th>Status</th>
                                <th>Zugewiesen an</th>
                                <th>Beschreibung</th>
                                <th>Erstellt von</th>
                                <th>Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredKeys.length === 0 ? (
                                <tr>
                                    <td colSpan="7" className="text-center">Keine FIDO-Keys gefunden</td>
                                </tr>
                            ) : (
                                filteredKeys.map((key) => (
                                    <tr key={key.id}>
                                        <td>{key.name}</td>
                                        <td><code style={{fontSize:12}}>{key.serial_number}</code></td>
                                        <td>
                                            <span className={`status-badge status-${key.status}`}>{key.status}</span>
                                        </td>
                                        <td>
                                            {key.assigned_to_username ? (
                                                <div style={{display:'flex',alignItems:'center',gap:6}}>
                                                    <div style={{width:24,height:24,borderRadius:'50%',background:'var(--cereda-primary)',color:'#fff',fontSize:10,display:'flex',alignItems:'center',justifyContent:'center',fontWeight:600,flexShrink:0}}>
                                                        {(key.assigned_to_username||'?').charAt(0).toUpperCase()}
                                                    </div>
                                                    <span style={{fontSize:13}}>{key.assigned_to_username}</span>
                                                    {canModifyFidoKeys() && (
                                                        <button
                                                            onClick={() => handleUnassign(key)}
                                                            title="Zuweisung aufheben"
                                                            style={{background:'none',border:'none',cursor:'pointer',color:'var(--text-muted)',padding:0,fontSize:14,lineHeight:1}}
                                                        >×</button>
                                                    )}
                                                </div>
                                            ) : (
                                                <span style={{color:'var(--text-muted)',fontSize:12}}>— nicht zugewiesen</span>
                                            )}
                                        </td>
                                        <td>{key.description || '-'}</td>
                                        <td>{key.created_by_username}</td>
                                        <td>
                                            <div className="table-actions">
                                                {canModifyFidoKeys() && (
                                                    <>
                                                        <button onClick={() => handleEdit(key)} className="btn btn-primary btn-small">Bearbeiten</button>
                                                        <button onClick={() => handleStatusToggle(key)} className="btn btn-secondary btn-small">
                                                            {key.status === 'aktiv' ? 'Deaktivieren' : 'Aktivieren'}
                                                        </button>
                                                    </>
                                                )}
                                                {isAdmin() && (
                                                    <button onClick={() => handleDelete(key.id)} className="btn btn-danger btn-small">Löschen</button>
                                                )}
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>

                {showModal && (
                    <div className="modal-overlay" onClick={() => setShowModal(false)}>
                        <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                            <div className="modal-header">
                                <h2 className="modal-title">{editingKey ? 'FIDO-Key bearbeiten' : 'Neuer FIDO-Key'}</h2>
                                <button className="modal-close" onClick={() => setShowModal(false)}>×</button>
                            </div>

                            <form onSubmit={handleSubmit}>
                                <div className="form-group">
                                    <label className="form-label">Name*</label>
                                    <input type="text" className="form-input" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} required />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Seriennummer*</label>
                                    <input type="text" className="form-input" value={formData.serial_number} onChange={(e) => setFormData({ ...formData, serial_number: e.target.value })} required />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Status*</label>
                                    <select className="form-select" value={formData.status} onChange={(e) => setFormData({ ...formData, status: e.target.value })} required>
                                        <option value="aktiv">Aktiv</option>
                                        <option value="inaktiv">Inaktiv</option>
                                    </select>
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Zugewiesen an</label>
                                    <select
                                        className="form-select"
                                        value={formData.assigned_to_user_id}
                                        onChange={(e) => setFormData({ ...formData, assigned_to_user_id: e.target.value })}
                                    >
                                        <option value="">— Nicht zugewiesen</option>
                                        {users.map(u => (
                                            <option key={u.id} value={u.id}>
                                                {u.full_name || u.username} ({u.email})
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Beschreibung</label>
                                    <textarea className="form-textarea" rows="3" value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} />
                                </div>

                                <div className="card-footer">
                                    <button type="button" onClick={() => setShowModal(false)} className="btn btn-secondary">Abbrechen</button>
                                    <button type="submit" className="btn btn-primary">Speichern</button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default FidoKeysPage;
