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: '',
        pin: '',
        assigned_to_user_id: '',
    });
    const [revealedPins, setRevealedPins] = useState({});

    const togglePinReveal = (id) => {
        setRevealedPins(prev => ({ ...prev, [id]: !prev[id] }));
        if (!revealedPins[id]) {
            setTimeout(() => setRevealedPins(prev => ({ ...prev, [id]: false })), 8000);
        }
    };

    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: '', pin: '', 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 || '',
            pin: key.pin || '',
            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>PIN</th>
                                <th>Beschreibung</th>
                                <th>Erstellt von</th>
                                <th>Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredKeys.length === 0 ? (
                                <tr>
                                    <td colSpan="8" className="text-center">Keine FIDO-Keys gefunden</td>
                                </tr>
                            ) : (
                                filteredKeys.map((key) => (
                                    <tr key={key.id}>
                                        <td>
                                            <div style={{display:'flex',alignItems:'center',gap:10,fontWeight:600}}>
                                                <div style={{width:32,height:32,borderRadius:8,background:'rgba(63,163,163,0.12)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                                                    <svg viewBox="0 0 24 24" fill="none" stroke="var(--cereda-primary)" strokeWidth="2" width="16" height="16"><circle cx="8" cy="8" r="5"/><path d="M10.5 12.5 19 21M16 16l2-2M19 19l2-2"/></svg>
                                                </div>
                                                {key.name}
                                            </div>
                                        </td>
                                        <td><span style={{fontFamily:'Consolas,monospace',background:'var(--bg-tertiary)',border:'1px solid var(--border-color)',borderRadius:6,padding:'3px 8px',fontSize:12,color:'var(--text-muted)'}}>{key.serial_number}</span></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.pin ? (
                                                <div style={{display:'flex',alignItems:'center',gap:8}}>
                                                    <span style={{fontFamily:'Consolas,monospace',background:'var(--bg-tertiary)',border:'1px solid var(--border-color)',borderRadius:6,padding:'3px 10px',fontSize:13,letterSpacing:'0.15em',minWidth:64,textAlign:'center',display:'inline-block'}}>
                                                        {revealedPins[key.id] ? key.pin : '••••••'}
                                                    </span>
                                                    <button
                                                        onClick={() => togglePinReveal(key.id)}
                                                        title={revealedPins[key.id] ? 'PIN verbergen' : 'PIN anzeigen'}
                                                        style={{background:'none',border:'none',cursor:'pointer',color:'var(--text-muted)',padding:2,display:'flex',alignItems:'center'}}
                                                    >
                                                        {revealedPins[key.id] ? (
                                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="16" height="16"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-7-11-7a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 7 11 7a18.5 18.5 0 0 1-2.16 3.19M14.12 14.12a3 3 0 1 1-4.24-4.24"/><path d="M1 1l22 22"/></svg>
                                                        ) : (
                                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="16" height="16"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7Z"/><circle cx="12" cy="12" r="3"/></svg>
                                                        )}
                                                    </button>
                                                </div>
                                            ) : (
                                                <span style={{color:'var(--text-muted)',fontSize:12}}>— keine PIN</span>
                                            )}
                                        </td>
                                        <td>{key.description || '-'}</td>
                                        <td>{key.created_by_username}</td>
                                        <td>
                                            <div className="table-actions">
                                                {canModifyFidoKeys() && (
                                                    <>
                                                        <button onClick={() => handleEdit(key)} title="Bearbeiten" className="btn btn-secondary btn-small" style={{width:32,padding:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
                                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
                                                        </button>
                                                        <button onClick={() => handleStatusToggle(key)} title={key.status === 'aktiv' ? 'Deaktivieren' : 'Aktivieren'} className="btn btn-secondary btn-small" style={{width:32,padding:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
                                                            {key.status === 'aktiv' ? (
                                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
                                                            ) : (
                                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><path d="M5 3l16 9-16 9V3z"/></svg>
                                                            )}
                                                        </button>
                                                    </>
                                                )}
                                                {isAdmin() && (
                                                    <button onClick={() => handleDelete(key.id)} title="Löschen" className="btn btn-danger btn-small" style={{width:32,padding:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
                                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0-1 14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2L4 6"/></svg>
                                                    </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">PIN</label>
                                    <input
                                        type="text"
                                        className="form-input"
                                        maxLength={6}
                                        pattern="[0-9]{6}"
                                        placeholder="6-stellige PIN"
                                        value={formData.pin}
                                        onChange={(e) => setFormData({ ...formData, pin: e.target.value.replace(/\D/g, '').slice(0, 6) })}
                                        style={{fontFamily:'Consolas,monospace',letterSpacing:'0.2em'}}
                                    />
                                </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;
