import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import ticketService from '../services/ticketService';
import userService from '../services/userService';
import assetService from '../services/assetService';
import api from '../services/api';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';

const PRIORITY_ICONS  = { niedrig: '🟢', mittel: '🔵', hoch: '🟠', kritisch: '🔴' };

const STATUS_CONFIG = {
    offen:                  { label: 'Offen',                  css: 'status-pending'     },
    in_bearbeitung:         { label: 'In Bearbeitung',         css: 'status-in_progress' },
    warten_auf_mitarbeiter: { label: 'Warten auf Mitarbeiter', css: 'status-completed'   },
    warten_auf_support:     { label: 'Warten auf Support',     css: 'status-warning'     },
    geschlossen:            { label: 'Geschlossen',            css: 'status-inaktiv'     },
};

const PRIORITY_CONFIG = {
    niedrig: { label: 'Niedrig', color: 'var(--success)'  },
    mittel:  { label: 'Mittel',  color: 'var(--info)'     },
    hoch:    { label: 'Hoch',    color: 'var(--warning)'  },
    kritisch:{ label: 'Kritisch',color: 'var(--danger)'   },
};

const StatCard = ({ icon, value, label, variant }) => (
    <div className={`stat-card ${variant}`} style={{ cursor: 'default' }}>
        <div className="stat-icon">{icon}</div>
        <div className="stat-content">
            <div className="stat-value">{value}</div>
            <div className="stat-label">{label}</div>
        </div>
    </div>
);

// SQLite gibt Timestamps ohne Timezone zurück → als UTC parsen
const toUTC = (d) => d ? new Date(typeof d === 'string' && !d.endsWith('Z') && !d.includes('+') ? d.replace(' ', 'T') + 'Z' : d) : null;

const formatDate = (d) => {
    if (!d) return '–';
    const date = toUTC(d);
    const now  = new Date();
    const diff = Math.floor((now - date) / 1000);
    if (diff < 60)     return 'gerade eben';
    if (diff < 3600)   return `vor ${Math.floor(diff / 60)} Min`;
    if (diff < 86400)  return `vor ${Math.floor(diff / 3600)} Std`;
    if (diff < 604800) return `vor ${Math.floor(diff / 86400)} Tagen`;
    return date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });
};

const SLA_WARN = { kritisch: 4, hoch: 24, mittel: 72, niedrig: 168 };
const SLA_CRIT = { kritisch: 24, hoch: 48, mittel: 168, niedrig: 336 };

const getSlaInfo = (ticket) => {
    if (ticket.status === 'geschlossen') return null;
    const ageH = (Date.now() - toUTC(ticket.created_at)) / 3600000;
    const warn = SLA_WARN[ticket.priority] || 72;
    const crit = SLA_CRIT[ticket.priority] || 168;
    if (ageH >= crit) return { color: '#ef4444', bg: 'rgba(239,68,68,0.12)', label: ageH < 48 ? `${Math.round(ageH)}h` : `${Math.floor(ageH / 24)}T` };
    if (ageH >= warn) return { color: '#f59e0b', bg: 'rgba(245,158,11,0.12)', label: ageH < 48 ? `${Math.round(ageH)}h` : `${Math.floor(ageH / 24)}T` };
    return null;
};

// Kanban-Spalten (4 Spalten – geschlossen nur in Wissensdatenbank)
const KANBAN_COLS = [
    { key: 'offen',                  label: 'Offen',                  css: 'status-pending'     },
    { key: 'in_bearbeitung',         label: 'In Bearbeitung',         css: 'status-in_progress' },
    { key: 'warten_auf_mitarbeiter', label: 'Warten auf Mitarbeiter', css: 'status-completed'   },
    { key: 'warten_auf_support',     label: 'Warten auf Support',     css: 'status-warning'     },
];

// Kanban-Karte
const KanbanCard = ({ ticket, onClick, onStatusChange, onClose, onDragStart, onDragEnd, isDragging }) => {
    const prioConf = PRIORITY_CONFIG[ticket.priority] || {};
    const slaInfo  = getSlaInfo(ticket);
    const assignee = ticket.assigned_to_first_name
        ? `${ticket.assigned_to_first_name} ${ticket.assigned_to_last_name || ''}`.trim()
        : ticket.assigned_to_username;

    return (
        <div
            draggable
            onDragStart={(e) => { e.dataTransfer.effectAllowed = 'move'; onDragStart(ticket.id); }}
            onDragEnd={onDragEnd}
            onClick={() => onClick(ticket.id)}
            style={{
                background: 'var(--bg-card)',
                border: '1px solid var(--border-color)',
                borderLeft: `3px solid ${prioConf.color}`,
                borderRadius: '8px',
                padding: '12px',
                marginBottom: '8px',
                cursor: 'grab',
                transition: 'box-shadow 0.15s, opacity 0.15s',
                opacity: isDragging ? 0.4 : 1,
                userSelect: 'none',
            }}
            onMouseEnter={e => e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)'}
            onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}
        >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '6px' }}>
                <span style={{ fontFamily: 'monospace', fontSize: '0.75rem', fontWeight: 700, color: 'var(--cereda-primary)' }}>
                    {ticket.ticket_number}
                </span>
                <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                    {slaInfo && (
                        <span style={{ fontSize: '10px', fontWeight: 700, padding: '1px 5px', borderRadius: '4px', background: slaInfo.bg, color: slaInfo.color }}>
                            ⏱ {slaInfo.label}
                        </span>
                    )}
                    <span style={{ fontSize: '14px' }}>{PRIORITY_ICONS[ticket.priority]}</span>
                </div>
            </div>
            <div style={{ fontSize: '0.8125rem', fontWeight: 600, color: 'var(--text-primary)', marginBottom: '8px', lineHeight: 1.4 }}>
                {ticket.title}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '0.75rem', color: 'var(--text-muted)' }}>
                <span>{ticket.category}</span>
                {assignee && (
                    <div style={{ width: '22px', height: '22px', borderRadius: '50%', background: 'linear-gradient(135deg, var(--cereda-primary), var(--cereda-accent))', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '9px', fontWeight: 700, color: 'white' }}>
                        {assignee.split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2)}
                    </div>
                )}
            </div>
            {/* Schnell-Status-Änderung */}
            <div style={{ display: 'flex', gap: '4px', marginTop: '8px', flexWrap: 'wrap' }} onClick={e => e.stopPropagation()}>
                {KANBAN_COLS.filter(c => c.key !== ticket.status).map(c => (
                    <button
                        key={c.key}
                        onClick={() => onStatusChange(ticket.id, c.key)}
                        style={{
                            fontSize: '10px', padding: '2px 6px', borderRadius: '4px',
                            border: '1px solid var(--border-color)', background: 'var(--bg-tertiary)',
                            color: 'var(--text-muted)', cursor: 'pointer',
                        }}
                        onMouseEnter={e => { e.target.style.background = 'var(--bg-secondary)'; e.target.style.color = 'var(--text-primary)'; }}
                        onMouseLeave={e => { e.target.style.background = 'var(--bg-tertiary)'; e.target.style.color = 'var(--text-muted)'; }}
                    >
                        → {c.label}
                    </button>
                ))}
                <button
                    onClick={() => onClose(ticket.id)}
                    style={{
                        fontSize: '10px', padding: '2px 6px', borderRadius: '4px',
                        border: '1px solid rgba(239,68,68,0.4)', background: 'rgba(239,68,68,0.08)',
                        color: 'var(--danger)', cursor: 'pointer',
                    }}
                    onMouseEnter={e => { e.target.style.background = 'rgba(239,68,68,0.18)'; }}
                    onMouseLeave={e => { e.target.style.background = 'rgba(239,68,68,0.08)'; }}
                >
                    ✓ Schließen
                </button>
            </div>
        </div>
    );
};

const TicketsPage = () => {
    const navigate = useNavigate();

    const [tickets,        setTickets]        = useState([]);
    const [stats,          setStats]          = useState(null);
    const [loading,        setLoading]        = useState(true);
    const [showModal,      setShowModal]      = useState(false);
    const [assets,         setAssets]         = useState([]);
    const [users,          setUsers]          = useState([]);
    const [searchTerm,     setSearchTerm]     = useState('');
    const [categories,     setCategories]     = useState([]);
    const [templates,      setTemplates]      = useState([]);
    const [statusFilter,   setStatusFilter]   = useState('');
    const [priorityFilter, setPriorityFilter] = useState('');
    const [categoryFilter, setCategoryFilter] = useState('');
    const [userFilter,     setUserFilter]     = useState('');
    const [allUsers,       setAllUsers]       = useState([]);
    const [viewMode,       setViewMode]       = useState(() => localStorage.getItem('ticketsViewMode') || 'table');

    // Drag & Drop
    const [draggedId,   setDraggedId]         = useState(null);
    const [dragOverCol, setDragOverCol]       = useState(null);

    // Schließen-Modal
    const [closeModal,  setCloseModal]        = useState({ open: false, ticketId: null });
    const [closeText,   setCloseText]         = useState('');
    const [closeLoading,setCloseLoading]      = useState(false);

    // Bulk-Aktionen
    const [selectedIds, setSelectedIds]       = useState(new Set());
    const [bulkAction,  setBulkAction]        = useState('');
    const [bulkAssignee,setBulkAssignee]      = useState('');
    const [bulkLoading, setBulkLoading]       = useState(false);

    const [formData,    setFormData]          = useState({
        title: '', description: '', category: 'Allgemein',
        priority: 'mittel', asset_id: '', requester_name: '', requester_email: '',
    });
    const [formLoading, setFormLoading] = useState(false);

    useEffect(() => { loadAll(); }, [statusFilter, priorityFilter, categoryFilter, searchTerm, userFilter]);
    useEffect(() => {
        // Lade alle offenen Tickets um zu sehen wer aktive Tickets hat
        Promise.all([
            userService.getAll(),
            ticketService.getAll({ status: 'offen' }),
            ticketService.getAll({ status: 'in_bearbeitung' }),
        ]).then(([users, offen, inBearbeitung]) => {
            const activeTickets = [...offen, ...inBearbeitung];
            const activeUserIds = new Set(activeTickets.map(t => t.assigned_to_user_id).filter(Boolean));
            const staffRoles = ['super_admin', 'admin', 'support', 'bearbeiter'];
            setAllUsers(users.filter(u => staffRoles.includes(u.role_name) && activeUserIds.has(u.id)));
        }).catch(() => {});
    }, []);

    // Auto-refresh alle 30 Sekunden
    useEffect(() => {
        const interval = setInterval(() => { loadAll(); }, 30000);
        return () => clearInterval(interval);
    }, [statusFilter, priorityFilter, categoryFilter, searchTerm]);

    useEffect(() => {
        if (showModal && assets.length === 0) {
            assetService.getAll().then(setAssets).catch(() => {});
        }
    }, [showModal]);

    useEffect(() => {
        if (users.length === 0) {
            userService.getAll().then(u => setUsers(u.filter(x => ['super_admin','admin','support'].includes(x.role_name)))).catch(() => {});
        }
    }, []);

    useEffect(() => {
        Promise.all([
            api.get('/settings/categories'),
            api.get('/settings/templates'),
        ]).then(([catRes, tplRes]) => {
            setCategories(catRes.data);
            setTemplates(tplRes.data);
        }).catch(() => {});
    }, []);

    const loadAll = async () => {
        try {
            const [ticketData, statsData] = await Promise.all([
                ticketService.getAll({
                    status:   statusFilter   || undefined,
                    priority: priorityFilter || undefined,
                    category: categoryFilter || undefined,
                    search:   searchTerm     || undefined,
                    assigned_to: userFilter || undefined,
                }),
                ticketService.getStats(),
            ]);
            setTickets(ticketData);
            setStats(statsData);
        } catch {
            toast.error('Fehler beim Laden der Tickets');
        } finally {
            setLoading(false);
        }
    };

    const handleCreate = async (e) => {
        e.preventDefault();
        setFormLoading(true);
        try {
            const ticket = await ticketService.create({
                ...formData,
                asset_id: formData.asset_id || undefined,
            });
            toast.success(`Ticket ${ticket.ticket_number} erstellt`);
            setShowModal(false);
            resetForm();
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler beim Erstellen');
        } finally {
            setFormLoading(false);
        }
    };

    const resetForm = () => setFormData({
        title: '', description: '', category: 'Allgemein',
        priority: 'mittel', asset_id: '', requester_name: '', requester_email: '',
    });

    const toggleFilter = (type, val) => {
        if (type === 'status')   setStatusFilter(v => v === val ? '' : val);
        if (type === 'priority') setPriorityFilter(v => v === val ? '' : val);
    };

    // Selektion
    const toggleSelect = (id) => {
        setSelectedIds(prev => {
            const next = new Set(prev);
            if (next.has(id)) next.delete(id); else next.add(id);
            return next;
        });
    };
    const toggleSelectAll = () => {
        if (selectedIds.size === tickets.length) {
            setSelectedIds(new Set());
        } else {
            setSelectedIds(new Set(tickets.map(t => t.id)));
        }
    };

    const handleBulkSubmit = async () => {
        if (!bulkAction || selectedIds.size === 0) return;
        setBulkLoading(true);
        try {
            const data = {};
            if (bulkAction === 'assign') data.assigned_to_user_id = bulkAssignee || null;
            else data.status = bulkAction;

            await ticketService.bulkUpdate([...selectedIds], data);
            toast.success(`${selectedIds.size} Ticket(s) aktualisiert`);
            setSelectedIds(new Set());
            setBulkAction('');
            setBulkAssignee('');
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler bei Bulk-Aktion');
        } finally {
            setBulkLoading(false);
        }
    };

    const handleKanbanStatusChange = async (ticketId, newStatus) => {
        if (newStatus === 'geschlossen') { requestClose(ticketId); return; }
        try {
            await ticketService.update(ticketId, { status: newStatus });
            setTickets(prev => prev.map(t => t.id === ticketId ? { ...t, status: newStatus } : t));
            toast.success('Status geändert');
        } catch {
            toast.error('Fehler beim Ändern');
        }
    };

    const requestClose = (ticketId) => {
        setCloseModal({ open: true, ticketId });
        setCloseText('');
    };

    const handleClose = async () => {
        setCloseLoading(true);
        try {
            await ticketService.update(closeModal.ticketId, { status: 'geschlossen' });
            if (closeText.trim()) {
                await ticketService.addComment(closeModal.ticketId, `Lösung: ${closeText.trim()}`, false);
            }
            setTickets(prev => prev.filter(t => t.id !== closeModal.ticketId));
            setCloseModal({ open: false, ticketId: null });
            toast.success('Ticket geschlossen & in Wissensdatenbank archiviert');
        } catch {
            toast.error('Fehler beim Schließen');
        } finally {
            setCloseLoading(false);
        }
    };

    const handleDrop = (targetColKey) => {
        if (!draggedId) return;
        const ticket = tickets.find(t => t.id === draggedId);
        if (!ticket || ticket.status === targetColKey) { setDraggedId(null); setDragOverCol(null); return; }
        handleKanbanStatusChange(draggedId, targetColKey);
        setDraggedId(null);
        setDragOverCol(null);
    };

    if (loading) return <LoadingSpinner />;

    const allSelected = selectedIds.size > 0 && selectedIds.size === tickets.length;
    const someSelected = selectedIds.size > 0;

    return (
        <div className="main-content">
            <div className="container">

                {/* Header */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem' }}>
                    <div>
                        <h1 style={{ margin: 0, fontSize: '1.75rem', fontWeight: 800, color: 'var(--text-primary)' }}>🎫 Tickets</h1>
                        <p style={{ margin: '4px 0 0', color: 'var(--text-secondary)', fontSize: '0.875rem' }}>
                            {tickets.length} Ticket{tickets.length !== 1 ? 's' : ''}{statusFilter ? ` · Filter: ${STATUS_CONFIG[statusFilter]?.label}` : ''}
                        </p>
                    </div>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                        <button onClick={() => navigate('/ticket-metrics')} className="btn btn-secondary">
                            📊 Metriken
                        </button>
                        {/* View toggle */}
                        <div style={{ display: 'flex', border: '1px solid var(--border-color)', borderRadius: '8px', overflow: 'hidden' }}>
                            <button
                                onClick={() => { setViewMode('table'); localStorage.setItem('ticketsViewMode', 'table'); }}
                                style={{ padding: '6px 12px', border: 'none', cursor: 'pointer', background: viewMode === 'table' ? 'var(--cereda-primary)' : 'var(--bg-secondary)', color: viewMode === 'table' ? 'white' : 'var(--text-secondary)', fontSize: '0.8125rem' }}
                            >☰ Tabelle</button>
                            <button
                                onClick={() => { setViewMode('kanban'); localStorage.setItem('ticketsViewMode', 'kanban'); }}
                                style={{ padding: '6px 12px', border: 'none', cursor: 'pointer', background: viewMode === 'kanban' ? 'var(--cereda-primary)' : 'var(--bg-secondary)', color: viewMode === 'kanban' ? 'white' : 'var(--text-secondary)', fontSize: '0.8125rem' }}
                            >⬛ Kanban</button>
                        </div>
                        <button className="btn btn-primary" onClick={() => setShowModal(true)}>+ Neues Ticket</button>
                    </div>
                </div>

                {/* Stats */}
                {stats && (
                    <div className="dashboard-grid" style={{ marginBottom: '2rem' }}>
                        <StatCard icon="📋" value={stats.total}      label="Gesamt"         variant="stat-card-primary" />
                        <StatCard icon="🔓" value={stats.open}       label="Offen"          variant="stat-card-warning" />
                        <StatCard icon="⚙️" value={stats.inProgress} label="In Bearbeitung" variant="stat-card-info"    />
                        <StatCard icon="🚨" value={stats.critical}   label="Kritisch offen" variant="stat-card-danger"  />
                    </div>
                )}

                {/* Filter Bar */}
                <div className="card" style={{ padding: '1rem 1.25rem', marginBottom: '1.5rem' }}>
                    <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', alignItems: 'center' }}>
                        <div style={{ flex: 1, minWidth: '200px', position: 'relative' }}>
                            <span style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)' }}>🔍</span>
                            <input type="text" className="form-input" placeholder="Ticket suchen..."
                                value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
                                style={{ paddingLeft: '32px' }} />
                        </div>
                        <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                            {Object.entries(STATUS_CONFIG).filter(([key]) => key !== 'geschlossen').map(([key, cfg]) => (
                                <button key={key} onClick={() => toggleFilter('status', key)}
                                    className={statusFilter === key ? 'btn btn-primary btn-small' : 'btn btn-secondary btn-small'}
                                    style={{ fontSize: '0.75rem' }}>
                                    {cfg.label}
                                </button>
                            ))}
                        </div>
                        <select className="form-select" value={userFilter} onChange={(e) => setUserFilter(e.target.value)} style={{ width: 'auto', minWidth: '160px' }}>
                            <option value="">👤 Alle Mitarbeiter</option>
                            {allUsers.map(u => (
                                <option key={u.id} value={u.id}>
                                    {u.first_name || u.last_name ? `${u.first_name || ''} ${u.last_name || ''}`.trim() : u.username}
                                </option>
                            ))}
                        </select>
                        <select className="form-select" value={priorityFilter} onChange={(e) => setPriorityFilter(e.target.value)} style={{ width: 'auto', minWidth: '130px' }}>
                            <option value="">Priorität (alle)</option>
                            <option value="kritisch">🔴 Kritisch</option>
                            <option value="hoch">🟠 Hoch</option>
                            <option value="mittel">🔵 Mittel</option>
                            <option value="niedrig">🟢 Niedrig</option>
                        </select>
                        <select className="form-select" value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)} style={{ width: 'auto', minWidth: '130px' }}>
                            <option value="">Kategorie (alle)</option>
                            {categories.map(c => <option key={c.id} value={c.name}>{c.icon} {c.name}</option>)}
                        </select>
                    </div>
                </div>

                {/* Bulk-Aktionen Bar */}
                {someSelected && viewMode === 'table' && (
                    <div style={{
                        background: 'var(--cereda-primary)', color: 'white',
                        borderRadius: '10px', padding: '12px 16px', marginBottom: '12px',
                        display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap',
                    }}>
                        <span style={{ fontWeight: 700, fontSize: '0.875rem' }}>
                            {selectedIds.size} ausgewählt
                        </span>
                        <select
                            value={bulkAction}
                            onChange={e => setBulkAction(e.target.value)}
                            style={{ padding: '4px 8px', borderRadius: '6px', border: 'none', fontSize: '0.8125rem', minWidth: '160px' }}
                        >
                            <option value="">Aktion wählen…</option>
                            <option value="offen">→ Offen</option>
                            <option value="in_bearbeitung">→ In Bearbeitung</option>
                            <option value="warten_auf_mitarbeiter">→ Warten auf Mitarbeiter</option>
                            <option value="warten_auf_support">→ Warten auf Support</option>
                            <option value="geschlossen">→ Schließen</option>
                            <option value="assign">→ Zuweisen an…</option>
                        </select>
                        {bulkAction === 'assign' && (
                            <select
                                value={bulkAssignee}
                                onChange={e => setBulkAssignee(e.target.value)}
                                style={{ padding: '4px 8px', borderRadius: '6px', border: 'none', fontSize: '0.8125rem', minWidth: '140px' }}
                            >
                                <option value="">— Nicht zugewiesen</option>
                                {users.map(u => (
                                    <option key={u.id} value={u.id}>
                                        {u.first_name ? `${u.first_name} ${u.last_name}` : u.username}
                                    </option>
                                ))}
                            </select>
                        )}
                        <button
                            onClick={handleBulkSubmit}
                            disabled={!bulkAction || bulkLoading}
                            style={{ padding: '4px 14px', borderRadius: '6px', border: 'none', background: 'white', color: 'var(--cereda-primary)', fontWeight: 700, cursor: 'pointer', fontSize: '0.8125rem' }}
                        >
                            {bulkLoading ? '⏳' : '✓ Anwenden'}
                        </button>
                        <button onClick={() => setSelectedIds(new Set())} style={{ marginLeft: 'auto', background: 'none', border: '1px solid rgba(255,255,255,0.4)', color: 'white', borderRadius: '6px', padding: '4px 10px', cursor: 'pointer', fontSize: '0.8125rem' }}>
                            Abbrechen
                        </button>
                    </div>
                )}

                {tickets.length === 0 ? (
                    <div className="card" style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-muted)' }}>
                        <div style={{ fontSize: '3rem', marginBottom: '1rem' }}>🎫</div>
                        <h3 style={{ color: 'var(--text-secondary)', margin: '0 0 8px' }}>Keine Tickets gefunden</h3>
                        <p style={{ margin: 0, fontSize: '0.875rem' }}>
                            {statusFilter || priorityFilter || categoryFilter || searchTerm ? 'Versuche die Filter anzupassen' : 'Erstelle das erste Ticket'}
                        </p>
                    </div>
                ) : viewMode === 'kanban' ? (
                    /* ── KANBAN VIEW ── */
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: '16px', alignItems: 'start' }}>
                        {KANBAN_COLS.map(col => {
                            const colTickets = tickets.filter(t => t.status === col.key);
                            const isOver = dragOverCol === col.key;
                            return (
                                <div
                                    key={col.key}
                                    onDragOver={(e) => { e.preventDefault(); setDragOverCol(col.key); }}
                                    onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget)) setDragOverCol(null); }}
                                    onDrop={() => handleDrop(col.key)}
                                    style={{
                                        background: isOver ? 'rgba(99,102,241,0.08)' : 'var(--bg-secondary)',
                                        borderRadius: '10px', padding: '12px',
                                        border: isOver ? '2px dashed var(--cereda-primary)' : '2px solid transparent',
                                        transition: 'background 0.15s, border 0.15s',
                                    }}
                                >
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                                        <span className={`status-badge ${col.css}`}>{col.label}</span>
                                        <span style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-muted)', background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: '10px', padding: '1px 7px' }}>
                                            {colTickets.length}
                                        </span>
                                    </div>
                                    <div style={{ minHeight: '60px' }}>
                                        {colTickets.map(ticket => (
                                            <KanbanCard
                                                key={ticket.id}
                                                ticket={ticket}
                                                isDragging={draggedId === ticket.id}
                                                onClick={(id) => navigate(`/tickets/${id}`)}
                                                onStatusChange={handleKanbanStatusChange}
                                                onClose={requestClose}
                                                onDragStart={setDraggedId}
                                                onDragEnd={() => { setDraggedId(null); setDragOverCol(null); }}
                                            />
                                        ))}
                                        {colTickets.length === 0 && (
                                            <div style={{ textAlign: 'center', padding: '20px 0', color: 'var(--text-muted)', fontSize: '0.8125rem' }}>
                                                {isOver ? '📥 Hier ablegen' : 'Leer'}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    /* ── TABLE VIEW ── */
                    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
                        <table className="table">
                            <thead>
                                <tr>
                                    <th style={{ width: '36px' }}>
                                        <input type="checkbox" checked={allSelected} onChange={toggleSelectAll}
                                            style={{ cursor: 'pointer', accentColor: 'var(--cereda-primary)' }} />
                                    </th>
                                    <th style={{ width: '40px' }}></th>
                                    <th style={{ width: '130px' }}>Ticket-Nr.</th>
                                    <th>Titel</th>
                                    <th style={{ width: '110px' }}>Kategorie</th>
                                    <th style={{ width: '120px' }}>Priorität</th>
                                    <th style={{ width: '140px' }}>Status</th>
                                    <th style={{ width: '150px' }}>Zugewiesen</th>
                                    <th style={{ width: '110px' }}>Erstellt</th>
                                    <th style={{ width: '100px' }}></th>
                                </tr>
                            </thead>
                            <tbody>
                                {tickets.filter(t => t.status !== 'geschlossen').map(ticket => {
                                    const prioConf   = PRIORITY_CONFIG[ticket.priority] || {};
                                    const statusConf = STATUS_CONFIG[ticket.status]     || {};
                                    const slaInfo    = getSlaInfo(ticket);
                                    const assignee   = ticket.assigned_to_first_name
                                        ? `${ticket.assigned_to_first_name} ${ticket.assigned_to_last_name || ''}`.trim()
                                        : ticket.assigned_to_username;
                                    const initials = assignee
                                        ? assignee.split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2)
                                        : null;
                                    const isSelected = selectedIds.has(ticket.id);
                                    return (
                                        <tr key={ticket.id} style={{ cursor: 'pointer', background: isSelected ? 'rgba(var(--cereda-primary-rgb, 99,102,241), 0.06)' : undefined }}
                                            onClick={() => navigate(`/tickets/${ticket.id}`)}>
                                            <td onClick={e => e.stopPropagation()}>
                                                <input type="checkbox" checked={isSelected} onChange={() => toggleSelect(ticket.id)}
                                                    style={{ cursor: 'pointer', accentColor: 'var(--cereda-primary)' }} />
                                            </td>
                                            <td style={{ padding: '0', width: '4px' }}>
                                                <div style={{ width: '4px', height: '100%', minHeight: '48px', background: prioConf.color, borderRadius: '2px' }} />
                                            </td>
                                            <td>
                                                <span style={{ fontFamily: 'monospace', fontSize: '0.8125rem', fontWeight: 700, color: 'var(--cereda-primary)' }}>
                                                    {ticket.ticket_number}
                                                </span>
                                                {ticket.source === 'email' && (
                                                    <span title="Via E-Mail" style={{ marginLeft: '5px', fontSize: '11px', opacity: 0.7 }}>📧</span>
                                                )}
                                            </td>
                                            <td>
                                                <span style={{ fontWeight: 500, color: 'var(--text-primary)' }}>{ticket.title}</span>
                                                {ticket.asset_name && (
                                                    <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '2px' }}>📦 {ticket.asset_name}</div>
                                                )}
                                            </td>
                                            <td>
                                                <span style={{ fontSize: '0.75rem', fontWeight: 600, padding: '2px 8px', borderRadius: '4px', background: 'var(--bg-tertiary)', color: 'var(--text-secondary)', border: '1px solid var(--border-color)' }}>
                                                    {ticket.category}
                                                </span>
                                            </td>
                                            <td>
                                                <span style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '0.8125rem', fontWeight: 600, color: prioConf.color }}>
                                                    {PRIORITY_ICONS[ticket.priority]} {prioConf.label}
                                                </span>
                                            </td>
                                            <td><span className={`status-badge ${statusConf.css}`}>{statusConf.label}</span></td>
                                            <td>
                                                {initials ? (
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                                        <div style={{ width: '28px', height: '28px', borderRadius: '50%', background: 'linear-gradient(135deg, var(--cereda-primary), var(--cereda-accent))', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, color: 'white', flexShrink: 0 }}>
                                                            {initials}
                                                        </div>
                                                        <span style={{ fontSize: '0.8125rem', color: 'var(--text-secondary)' }}>{assignee}</span>
                                                    </div>
                                                ) : (
                                                    <span style={{ fontSize: '0.8125rem', color: 'var(--text-muted)' }}>— nicht zugewiesen</span>
                                                )}
                                            </td>
                                            <td style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                                    {formatDate(ticket.created_at)}
                                                    {slaInfo && (
                                                        <span style={{ fontSize: '10px', fontWeight: 700, padding: '1px 5px', borderRadius: '4px', background: slaInfo.bg, color: slaInfo.color, border: `1px solid ${slaInfo.color}44`, whiteSpace: 'nowrap' }}>
                                                            ⏱ {slaInfo.label}
                                                        </span>
                                                    )}
                                                </div>
                                            </td>
                                            <td className="table-actions" onClick={(e) => e.stopPropagation()}>
                                                <button className="btn btn-secondary btn-small" onClick={() => navigate(`/tickets/${ticket.id}`)}>Öffnen</button>
                                                <a
                                                    href={ticketService.getPdfUrl(ticket.id)}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    className="btn btn-secondary btn-small"
                                                    style={{ textDecoration: 'none' }}
                                                    title="PDF exportieren"
                                                >
                                                    📄
                                                </a>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                )}

                {/* Schließen-Modal */}
                {closeModal.open && (
                    <div className="modal-overlay" onClick={() => setCloseModal({ open: false, ticketId: null })}>
                        <div className="modal-content" style={{ maxWidth: 480 }} onClick={e => e.stopPropagation()}>
                            <div className="modal-header">
                                <h2 className="modal-title">✅ Ticket schließen</h2>
                                <button className="modal-close" onClick={() => setCloseModal({ open: false, ticketId: null })}>×</button>
                            </div>
                            <div style={{ padding: '20px 24px' }}>
                                <p style={{ margin: '0 0 16px', fontSize: '0.875rem', color: 'var(--text-secondary)' }}>
                                    Das Ticket wird geschlossen und in die Wissensdatenbank übertragen. Eine Lösungsbeschreibung ist optional.
                                </p>
                                <div className="form-group">
                                    <label className="form-label">Lösungsbeschreibung (optional)</label>
                                    <textarea
                                        className="form-textarea"
                                        rows={4}
                                        placeholder="Was hat das Problem gelöst? (kann leer gelassen werden)"
                                        value={closeText}
                                        onChange={e => setCloseText(e.target.value)}
                                        autoFocus
                                    />
                                </div>
                                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
                                    <button className="btn btn-secondary" onClick={() => setCloseModal({ open: false, ticketId: null })} disabled={closeLoading}>
                                        Abbrechen
                                    </button>
                                    <button className="btn btn-secondary" onClick={handleClose} disabled={closeLoading} style={{ opacity: 0.7 }}>
                                        {closeLoading ? '⏳' : 'Schließen ohne Notiz'}
                                    </button>
                                    <button
                                        className="btn btn-primary"
                                        onClick={handleClose}
                                        disabled={closeLoading || !closeText.trim()}
                                        style={{ background: 'var(--success)', borderColor: 'var(--success)' }}
                                    >
                                        {closeLoading ? '⏳' : '✅ Lösung speichern & schließen'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Create Modal */}
                {showModal && (
                    <div className="modal-overlay" onClick={() => { setShowModal(false); resetForm(); }}>
                        <div className="modal-content modal-large" onClick={(e) => e.stopPropagation()}>
                            <div className="modal-header">
                                <h2 className="modal-title">🎫 Neues Ticket erstellen</h2>
                                <button className="modal-close" onClick={() => { setShowModal(false); resetForm(); }}>×</button>
                            </div>
                            <form onSubmit={handleCreate}>
                                <div className="form-group">
                                    <label className="form-label">Vorlage (optional)</label>
                                    <select className="form-select" defaultValue="" onChange={(e) => {
                                        const t = templates.find(x => String(x.id) === e.target.value);
                                        if (t) setFormData({ ...formData, title: t.title, description: t.description, category: t.category, priority: t.priority });
                                    }}>
                                        <option value="">— Vorlage wählen —</option>
                                        {templates.map(t => <option key={t.id} value={String(t.id)}>{t.label}</option>)}
                                    </select>
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Titel*</label>
                                    <input type="text" className="form-input" required value={formData.title}
                                        onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                                        placeholder="Kurze Beschreibung des Problems" autoFocus />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Beschreibung</label>
                                    <textarea className="form-textarea" rows="4" value={formData.description}
                                        onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                        placeholder="Detaillierte Beschreibung…" />
                                </div>
                                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                                    <div className="form-group">
                                        <label className="form-label">Kategorie</label>
                                        <select className="form-select" value={formData.category}
                                            onChange={(e) => setFormData({ ...formData, category: e.target.value })}>
                                            {categories.map(c => <option key={c.id} value={c.name}>{c.icon} {c.name}</option>)}
                                        </select>
                                    </div>
                                    <div className="form-group">
                                        <label className="form-label">Priorität</label>
                                        <select className="form-select" value={formData.priority}
                                            onChange={(e) => setFormData({ ...formData, priority: e.target.value })}>
                                            <option value="niedrig">🟢 Niedrig</option>
                                            <option value="mittel">🔵 Mittel</option>
                                            <option value="hoch">🟠 Hoch</option>
                                            <option value="kritisch">🔴 Kritisch</option>
                                        </select>
                                    </div>
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Betroffenes Asset (optional)</label>
                                    <select className="form-select" value={formData.asset_id}
                                        onChange={(e) => setFormData({ ...formData, asset_id: e.target.value })}>
                                        <option value="">— Kein Asset ausgewählt</option>
                                        {assets.map(a => <option key={a.id} value={a.id}>{a.name} · {a.serial_number}</option>)}
                                    </select>
                                </div>
                                <div style={{ borderTop: '1px solid var(--border-color)', margin: '16px 0 12px', paddingTop: '12px' }}>
                                    <p style={{ margin: '0 0 12px', fontSize: '0.8125rem', color: 'var(--text-muted)' }}>Anfragender (wird automatisch aus dem Login-Account befüllt)</p>
                                </div>
                                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                                    <div className="form-group">
                                        <label className="form-label">Name</label>
                                        <input type="text" className="form-input" value={formData.requester_name}
                                            onChange={(e) => setFormData({ ...formData, requester_name: e.target.value })}
                                            placeholder="Automatisch befüllt" />
                                    </div>
                                    <div className="form-group">
                                        <label className="form-label">E-Mail</label>
                                        <input type="email" className="form-input" value={formData.requester_email}
                                            onChange={(e) => setFormData({ ...formData, requester_email: e.target.value })}
                                            placeholder="Automatisch befüllt" />
                                    </div>
                                </div>
                                <div className="card-footer">
                                    <button type="button" className="btn btn-secondary" onClick={() => { setShowModal(false); resetForm(); }} disabled={formLoading}>Abbrechen</button>
                                    <button type="submit" className="btn btn-primary" disabled={formLoading}>
                                        {formLoading ? '⏳ Erstellen…' : '🎫 Ticket erstellen'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}

            </div>
        </div>
    );
};

export default TicketsPage;
