import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext';
import isoService from '../services/isoService';
import { toast } from 'react-toastify';

const CATEGORIES = [
    { key: 'Risikomanagement',    icon: '⚠️',  color: '#ef4444' },
    { key: 'TOM',                 icon: '🔒',  color: '#8b5cf6' },
    { key: 'Incident Management', icon: '🚨',  color: '#f97316' },
    { key: 'Business Continuity', icon: '♻️',  color: '#3b82f6' },
    { key: 'Dokumentation',       icon: '📄',  color: '#10b981' },
    { key: 'Awareness & Schulung',icon: '🎓',  color: '#f59e0b' },
];

const STATUS_OPTS = ['Offen', 'In Bearbeitung', 'Abgeschlossen'];

const STATUS_STYLE = {
    'Offen':           { bg: 'rgba(107,114,128,0.12)', text: '#9ca3af',  border: '#4b5563' },
    'In Bearbeitung':  { bg: 'rgba(245,158,11,0.12)',  text: '#f59e0b',  border: '#f59e0b' },
    'Abgeschlossen':   { bg: 'rgba(34,197,94,0.12)',   text: '#22c55e',  border: '#22c55e' },
};

const EMPTY_FORM = { category: 'Risikomanagement', title: '', description: '', responsible: '', notes: '', status: 'Offen' };

export default function IsoPage() {
    const { isAdmin } = useAuth();
    const canEdit = isAdmin();

    const [tasks, setTasks]         = useState([]);
    const [loading, setLoading]     = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [editing, setEditing]     = useState(null);
    const [form, setForm]           = useState(EMPTY_FORM);
    const [saving, setSaving]       = useState(false);
    const [deleteConfirm, setDeleteConfirm] = useState(null);
    const [expandedId, setExpandedId]       = useState(null);

    const load = useCallback(async () => {
        try {
            const data = await isoService.getAll();
            setTasks(data);
        } catch {
            toast.error('Fehler beim Laden der ISO-Aufgaben');
        } finally {
            setLoading(false);
        }
    }, []);

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

    const openNew = (category) => {
        setEditing(null);
        setForm({ ...EMPTY_FORM, category });
        setShowModal(true);
    };

    const openEdit = (task) => {
        setEditing(task);
        setForm({
            category:    task.category,
            title:       task.title,
            description: task.description || '',
            responsible: task.responsible || '',
            notes:       task.notes || '',
            status:      task.status,
        });
        setShowModal(true);
    };

    const save = async () => {
        if (!form.title.trim()) return;
        setSaving(true);
        try {
            if (editing) {
                await isoService.update(editing.id, form);
                toast.success('Gespeichert');
            } else {
                await isoService.create(form);
                toast.success('Aufgabe erstellt');
            }
            setShowModal(false);
            load();
        } catch {
            toast.error('Fehler beim Speichern');
        } finally {
            setSaving(false);
        }
    };

    const quickStatus = async (task) => {
        if (!canEdit) return;
        const next = STATUS_OPTS[(STATUS_OPTS.indexOf(task.status) + 1) % STATUS_OPTS.length];
        try {
            await isoService.update(task.id, { status: next });
            setTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: next } : t));
        } catch {
            toast.error('Fehler');
        }
    };

    const doDelete = async () => {
        if (!deleteConfirm) return;
        try {
            await isoService.delete(deleteConfirm.id);
            toast.success('Gelöscht');
            setDeleteConfirm(null);
            load();
        } catch {
            toast.error('Fehler beim Löschen');
        }
    };

    const total     = tasks.length;
    const done      = tasks.filter(t => t.status === 'Abgeschlossen').length;
    const inProgress = tasks.filter(t => t.status === 'In Bearbeitung').length;
    const progress  = total ? Math.round((done / total) * 100) : 0;

    if (loading) return <div style={{ display: 'flex', justifyContent: 'center', padding: '3rem' }}><div className="spinner" /></div>;

    return (
        <div style={{ maxWidth: 1400, margin: '0 auto' }}>
            {/* Header */}
            <div className="page-header" style={{ marginBottom: '1.5rem' }}>
                <div>
                    <h1 style={{ margin: 0, fontSize: '1.5rem', fontWeight: 700, color: '#f1f5f9' }}>
                        🛡️ ISO-Zertifizierung
                    </h1>
                    <p style={{ margin: '4px 0 0', color: '#64748b', fontSize: 14 }}>
                        Übersicht aller Maßnahmen für die ISO-Zertifizierung
                    </p>
                </div>
            </div>

            {/* Stats */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 24 }}>
                {[
                    { label: 'Gesamt',         value: total,      color: '#94a3b8' },
                    { label: 'In Bearbeitung', value: inProgress, color: '#f59e0b' },
                    { label: 'Abgeschlossen',  value: done,       color: '#22c55e' },
                    { label: 'Fortschritt',    value: `${progress}%`, color: '#0d9488' },
                ].map(s => (
                    <div key={s.label} className="card" style={{ padding: '1rem 1.25rem', textAlign: 'center' }}>
                        <div style={{ fontSize: '1.75rem', fontWeight: 700, color: s.color }}>{s.value}</div>
                        <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>{s.label}</div>
                    </div>
                ))}
            </div>

            {/* Progress bar */}
            <div className="card" style={{ padding: '0.875rem 1.25rem', marginBottom: 24 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontSize: 13, color: '#94a3b8' }}>
                    <span>Gesamtfortschritt</span>
                    <span style={{ color: '#0d9488', fontWeight: 600 }}>{progress}%</span>
                </div>
                <div style={{ height: 8, background: 'rgba(255,255,255,0.06)', borderRadius: 4, overflow: 'hidden' }}>
                    <div style={{
                        height: '100%', width: `${progress}%`,
                        background: 'linear-gradient(90deg, #0d9488, #14b8a6)',
                        borderRadius: 4, transition: 'width 0.5s ease',
                    }} />
                </div>
            </div>

            {/* Categories */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: 20 }}>
                {CATEGORIES.map(cat => {
                    const catTasks = tasks.filter(t => t.category === cat.key);
                    const catDone  = catTasks.filter(t => t.status === 'Abgeschlossen').length;
                    return (
                        <div key={cat.key} className="card" style={{ padding: 0, overflow: 'hidden' }}>
                            {/* Category header */}
                            <div style={{
                                padding: '0.875rem 1.125rem',
                                borderBottom: '1px solid rgba(255,255,255,0.06)',
                                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                background: `${cat.color}12`,
                            }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                    <span style={{ fontSize: 18 }}>{cat.icon}</span>
                                    <span style={{ fontWeight: 700, fontSize: 14, color: '#f1f5f9' }}>{cat.key}</span>
                                    <span style={{
                                        fontSize: 11, padding: '2px 8px', borderRadius: 20,
                                        background: `${cat.color}20`, color: cat.color, border: `1px solid ${cat.color}40`,
                                        fontWeight: 600,
                                    }}>{catDone}/{catTasks.length}</span>
                                </div>
                                {canEdit && (
                                    <button onClick={() => openNew(cat.key)} style={{
                                        background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)',
                                        color: '#94a3b8', borderRadius: 6, padding: '3px 10px', cursor: 'pointer',
                                        fontSize: 18, lineHeight: 1,
                                    }}>+</button>
                                )}
                            </div>

                            {/* Tasks */}
                            <div style={{ padding: '0.5rem' }}>
                                {catTasks.length === 0 && (
                                    <div style={{ padding: '1rem', color: '#475569', fontSize: 13, textAlign: 'center' }}>
                                        Keine Aufgaben
                                    </div>
                                )}
                                {catTasks.map(task => {
                                    const ss = STATUS_STYLE[task.status];
                                    const isExpanded = expandedId === task.id;
                                    return (
                                        <div key={task.id} style={{
                                            padding: '0.75rem',
                                            borderRadius: 8,
                                            marginBottom: 4,
                                            background: 'rgba(255,255,255,0.03)',
                                            border: '1px solid rgba(255,255,255,0.05)',
                                            cursor: 'pointer',
                                        }} onClick={() => setExpandedId(isExpanded ? null : task.id)}>
                                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                                                {/* Status toggle */}
                                                <button
                                                    onClick={(e) => { e.stopPropagation(); quickStatus(task); }}
                                                    title={`Status: ${task.status} → weiter`}
                                                    style={{
                                                        flexShrink: 0, width: 22, height: 22, borderRadius: '50%',
                                                        border: `2px solid ${ss.border}`,
                                                        background: task.status === 'Abgeschlossen' ? ss.border : 'transparent',
                                                        cursor: canEdit ? 'pointer' : 'default',
                                                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                                                        color: '#fff', fontSize: 12, marginTop: 1,
                                                    }}
                                                >
                                                    {task.status === 'Abgeschlossen' ? '✓' : task.status === 'In Bearbeitung' ? '◑' : ''}
                                                </button>

                                                <div style={{ flex: 1, minWidth: 0 }}>
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                                                        <span style={{
                                                            fontSize: 14, color: task.status === 'Abgeschlossen' ? '#475569' : '#e2e8f0',
                                                            fontWeight: 500,
                                                            textDecoration: task.status === 'Abgeschlossen' ? 'line-through' : 'none',
                                                        }}>{task.title}</span>
                                                        <span style={{
                                                            fontSize: 11, padding: '2px 7px', borderRadius: 20,
                                                            background: ss.bg, color: ss.text, border: `1px solid ${ss.border}40`,
                                                            fontWeight: 500, whiteSpace: 'nowrap',
                                                        }}>{task.status}</span>
                                                    </div>
                                                    {task.description && !isExpanded && (
                                                        <div style={{ fontSize: 12, color: '#64748b', marginTop: 3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                                            {task.description}
                                                        </div>
                                                    )}
                                                    {isExpanded && (
                                                        <div style={{ marginTop: 8 }}>
                                                            {task.description && (
                                                                <p style={{ fontSize: 13, color: '#94a3b8', margin: '0 0 8px' }}>{task.description}</p>
                                                            )}
                                                            {task.responsible && (
                                                                <div style={{ fontSize: 12, color: '#64748b' }}>👤 <span style={{ color: '#94a3b8' }}>{task.responsible}</span></div>
                                                            )}
                                                            {task.notes && (
                                                                <div style={{ fontSize: 12, color: '#64748b', marginTop: 4 }}>📝 <span style={{ color: '#94a3b8' }}>{task.notes}</span></div>
                                                            )}
                                                            {canEdit && (
                                                                <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                                                                    <button onClick={(e) => { e.stopPropagation(); openEdit(task); }} style={{
                                                                        background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
                                                                        color: '#94a3b8', borderRadius: 6, padding: '4px 12px',
                                                                        cursor: 'pointer', fontSize: 12,
                                                                    }}>✏️ Bearbeiten</button>
                                                                    <button onClick={(e) => { e.stopPropagation(); setDeleteConfirm(task); }} style={{
                                                                        background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)',
                                                                        color: '#ef4444', borderRadius: 6, padding: '4px 12px',
                                                                        cursor: 'pointer', fontSize: 12,
                                                                    }}>🗑️ Löschen</button>
                                                                </div>
                                                            )}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    );
                })}
            </div>

            {/* Modal */}
            {showModal && (
                <div className="modal-overlay" onClick={() => setShowModal(false)}>
                    <div className="modal-content modal-large" onClick={e => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>{editing ? 'Aufgabe bearbeiten' : 'Neue Aufgabe'}</h3>
                            <button className="modal-close" onClick={() => setShowModal(false)}>×</button>
                        </div>
                        <div className="modal-body">
                            <div className="form-group">
                                <label className="form-label">Kategorie</label>
                                <select className="form-select" value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))}>
                                    {CATEGORIES.map(c => <option key={c.key} value={c.key}>{c.icon} {c.key}</option>)}
                                </select>
                            </div>
                            <div className="form-group">
                                <label className="form-label">Titel *</label>
                                <input className="form-input" value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} placeholder="Aufgabentitel" />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Beschreibung</label>
                                <textarea className="form-input" rows={3} value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} placeholder="Was ist zu tun?" />
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                                <div className="form-group">
                                    <label className="form-label">Status</label>
                                    <select className="form-select" value={form.status} onChange={e => setForm(f => ({ ...f, status: e.target.value }))}>
                                        {STATUS_OPTS.map(s => <option key={s} value={s}>{s}</option>)}
                                    </select>
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Verantwortlicher</label>
                                    <input className="form-input" value={form.responsible} onChange={e => setForm(f => ({ ...f, responsible: e.target.value }))} placeholder="Name" />
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="form-label">Notizen</label>
                                <textarea className="form-input" rows={2} value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))} placeholder="Interne Notizen..." />
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button className="btn btn-secondary" onClick={() => setShowModal(false)}>Abbrechen</button>
                            <button className="btn btn-primary" onClick={save} disabled={saving || !form.title.trim()}>
                                {saving ? 'Speichern...' : 'Speichern'}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Delete confirm */}
            {deleteConfirm && (
                <div className="modal-overlay" onClick={() => setDeleteConfirm(null)}>
                    <div className="modal-content" onClick={e => e.stopPropagation()} style={{ maxWidth: 400 }}>
                        <div className="modal-header">
                            <h3>Aufgabe löschen</h3>
                            <button className="modal-close" onClick={() => setDeleteConfirm(null)}>×</button>
                        </div>
                        <div className="modal-body">
                            <p style={{ color: '#94a3b8' }}>„<strong style={{ color: '#f1f5f9' }}>{deleteConfirm.title}</strong>" wirklich löschen?</p>
                        </div>
                        <div className="modal-footer">
                            <button className="btn btn-secondary" onClick={() => setDeleteConfirm(null)}>Abbrechen</button>
                            <button className="btn btn-danger" onClick={doDelete}>Löschen</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
