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

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

const MetricCard = ({ icon, value, label, sub, color }) => (
    <div style={{
        background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: '12px',
        padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: '4px',
    }}>
        <div style={{ fontSize: '1.5rem', marginBottom: '4px' }}>{icon}</div>
        <div style={{ fontSize: '2rem', fontWeight: 800, color: color || 'var(--text-primary)', lineHeight: 1 }}>{value}</div>
        <div style={{ fontSize: '0.8125rem', fontWeight: 600, color: 'var(--text-primary)' }}>{label}</div>
        {sub && <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>{sub}</div>}
    </div>
);

const BarChart = ({ data, labelKey, valueKey, color = 'var(--cereda-primary)', maxItems = 30 }) => {
    if (!data || data.length === 0) return <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-muted)', fontSize: '0.875rem' }}>Keine Daten</div>;
    const max = Math.max(...data.map(d => d[valueKey] || 0), 1);
    const items = data.slice(-maxItems);
    return (
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: '4px', height: '120px', padding: '0 4px' }}>
            {items.map((d, i) => {
                const h = Math.round(((d[valueKey] || 0) / max) * 100);
                return (
                    <div key={i} title={`${d[labelKey]}: ${d[valueKey]}`} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '2px', height: '100%', justifyContent: 'flex-end', minWidth: 0 }}>
                        <div style={{ width: '100%', height: `${h}%`, background: color, borderRadius: '3px 3px 0 0', minHeight: d[valueKey] ? '4px' : 0, opacity: 0.85 }} />
                        {items.length <= 10 && (
                            <div style={{ fontSize: '9px', color: 'var(--text-muted)', textAlign: 'center', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', width: '100%' }}>
                                {String(d[labelKey]).slice(-5)}
                            </div>
                        )}
                    </div>
                );
            })}
        </div>
    );
};

const TicketMetricsPage = () => {
    const navigate = useNavigate();
    const [metrics, setMetrics] = useState(null);
    const [loading, setLoading] = useState(true);
    const [days, setDays]       = useState(30);

    useEffect(() => {
        loadMetrics();
    }, [days]);

    const loadMetrics = async () => {
        setLoading(true);
        try {
            const data = await ticketService.getMetrics(days);
            setMetrics(data);
        } catch {
            toast.error('Metriken konnten nicht geladen werden');
        } finally {
            setLoading(false);
        }
    };

    if (loading) return <LoadingSpinner />;
    if (!metrics) return null;

    const totalCreated = metrics.perDay.reduce((s, d) => s + d.created, 0);
    const totalResolved = metrics.perDay.reduce((s, d) => s + d.resolved, 0);
    const resolutionRate = totalCreated > 0 ? Math.round((totalResolved / totalCreated) * 100) : 0;
    const totalSlaBreaches = metrics.slaBreaches.reduce((s, d) => s + d.count, 0);

    const avgHours = metrics.avgResolution.find(r => r.priority === 'mittel')?.avg_hours || '–';

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

                {/* Header */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem' }}>
                    <div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                            <button className="btn btn-secondary btn-small" onClick={() => navigate('/tickets')} style={{ fontSize: '0.8125rem' }}>
                                ← Tickets
                            </button>
                        </div>
                        <h1 style={{ margin: 0, fontSize: '1.75rem', fontWeight: 800, color: 'var(--text-primary)' }}>📊 Ticket-Metriken</h1>
                        <p style={{ margin: '4px 0 0', color: 'var(--text-secondary)', fontSize: '0.875rem' }}>
                            Analyse der letzten {days} Tage
                        </p>
                    </div>
                    <div style={{ display: 'flex', border: '1px solid var(--border-color)', borderRadius: '8px', overflow: 'hidden' }}>
                        {[7, 14, 30, 90].map(d => (
                            <button key={d} onClick={() => setDays(d)} style={{
                                padding: '6px 14px', border: 'none', cursor: 'pointer', fontSize: '0.8125rem',
                                background: days === d ? 'var(--cereda-primary)' : 'var(--bg-secondary)',
                                color: days === d ? 'white' : 'var(--text-secondary)',
                            }}>
                                {d}T
                            </button>
                        ))}
                    </div>
                </div>

                {/* KPI-Karten */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', marginBottom: '2rem' }}>
                    <MetricCard icon="📋" value={totalCreated} label="Erstellt" sub={`letzte ${days} Tage`} />
                    <MetricCard icon="✅" value={totalResolved} label="Gelöst" sub={`letzte ${days} Tage`} color="var(--success)" />
                    <MetricCard icon="📈" value={`${resolutionRate}%`} label="Lösungsrate" color={resolutionRate >= 70 ? 'var(--success)' : resolutionRate >= 40 ? 'var(--warning)' : 'var(--danger)'} />
                    <MetricCard icon="🚨" value={totalSlaBreaches} label="SLA-Verletzungen" sub="offen & überfällig" color={totalSlaBreaches > 0 ? 'var(--danger)' : 'var(--success)'} />
                </div>

                {/* Tickets pro Tag */}
                <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '16px', marginBottom: '2rem' }}>
                    <div className="card" style={{ padding: '20px 24px' }}>
                        <h3 style={{ margin: '0 0 16px', fontSize: '0.875rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-muted)' }}>
                            Tickets pro Tag
                        </h3>
                        {metrics.perDay.length === 0 ? (
                            <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-muted)', fontSize: '0.875rem' }}>Keine Daten für diesen Zeitraum</div>
                        ) : (
                            <>
                                <div style={{ display: 'flex', alignItems: 'flex-end', gap: '3px', height: '120px', marginBottom: '8px' }}>
                                    {metrics.perDay.slice(-days).map((d, i) => {
                                        const maxVal = Math.max(...metrics.perDay.map(x => x.created), 1);
                                        const hC = Math.round((d.created / maxVal) * 100);
                                        const hR = Math.round((d.resolved / maxVal) * 100);
                                        return (
                                            <div key={i} title={`${d.date}: ${d.created} erstellt, ${d.resolved} gelöst`}
                                                style={{ flex: 1, display: 'flex', alignItems: 'flex-end', gap: '1px', height: '100%', justifyContent: 'center', minWidth: 0 }}>
                                                <div style={{ flex: 1, height: `${hC}%`, background: 'var(--cereda-primary)', borderRadius: '2px 2px 0 0', opacity: 0.8, minHeight: d.created ? '3px' : 0 }} />
                                                <div style={{ flex: 1, height: `${hR}%`, background: 'var(--success)', borderRadius: '2px 2px 0 0', opacity: 0.8, minHeight: d.resolved ? '3px' : 0 }} />
                                            </div>
                                        );
                                    })}
                                </div>
                                <div style={{ display: 'flex', gap: '16px', justifyContent: 'flex-end', fontSize: '0.75rem', color: 'var(--text-muted)' }}>
                                    <span><span style={{ display: 'inline-block', width: '10px', height: '10px', borderRadius: '2px', background: 'var(--cereda-primary)', marginRight: '4px', verticalAlign: 'middle' }} />Erstellt</span>
                                    <span><span style={{ display: 'inline-block', width: '10px', height: '10px', borderRadius: '2px', background: 'var(--success)', marginRight: '4px', verticalAlign: 'middle' }} />Gelöst</span>
                                </div>
                            </>
                        )}
                    </div>

                    {/* Nach Kategorie */}
                    <div className="card" style={{ padding: '20px 24px' }}>
                        <h3 style={{ margin: '0 0 16px', fontSize: '0.875rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-muted)' }}>
                            Nach Kategorie
                        </h3>
                        {metrics.byCategory.map(cat => {
                            const pct = cat.count > 0 ? Math.round((cat.open / cat.count) * 100) : 0;
                            const total = metrics.byCategory.reduce((s, c) => s + c.count, 0);
                            const barW = total > 0 ? Math.round((cat.count / total) * 100) : 0;
                            return (
                                <div key={cat.category} style={{ marginBottom: '12px' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', fontSize: '0.8125rem' }}>
                                        <span style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{cat.category}</span>
                                        <span style={{ color: 'var(--text-muted)' }}>{cat.count} ({pct}% offen)</span>
                                    </div>
                                    <div style={{ height: '6px', background: 'var(--bg-tertiary)', borderRadius: '3px', overflow: 'hidden' }}>
                                        <div style={{ height: '100%', width: `${barW}%`, background: 'var(--cereda-primary)', borderRadius: '3px', transition: 'width 0.3s' }} />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* Kundenfeedback */}
                {metrics.satisfactionTotal && (
                    <div style={{ marginBottom: '2rem' }}>
                        <h2 style={{ margin: '0 0 16px', fontSize: '0.875rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-muted)' }}>Kundenfeedback</h2>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 2fr', gap: '16px' }}>
                            <MetricCard icon="👍" value={metrics.satisfactionTotal.gut} label="Positiv" color="var(--success)" />
                            <MetricCard icon="👎" value={metrics.satisfactionTotal.schlecht} label="Negativ" color="var(--danger)" />
                            <MetricCard
                                icon="📊"
                                value={metrics.satisfactionTotal.total > 0
                                    ? `${Math.round((metrics.satisfactionTotal.gut / metrics.satisfactionTotal.total) * 100)}%`
                                    : '–'}
                                label="Zufriedenheitsrate"
                                color={metrics.satisfactionTotal.total > 0
                                    ? (metrics.satisfactionTotal.gut / metrics.satisfactionTotal.total) >= 0.7 ? 'var(--success)' : 'var(--warning)'
                                    : 'var(--text-muted)'}
                                sub={`${metrics.satisfactionTotal.total} Bewertungen gesamt`}
                            />
                            {/* Letzte Kommentare */}
                            <div className="card" style={{ padding: '20px 24px' }}>
                                <h3 style={{ margin: '0 0 14px', fontSize: '0.875rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-muted)' }}>
                                    Letzte Kommentare
                                </h3>
                                {metrics.recentFeedback.filter(f => f.satisfaction_comment).length === 0 ? (
                                    <div style={{ color: 'var(--text-muted)', fontSize: '0.875rem', textAlign: 'center', padding: '1.5rem 0' }}>
                                        Noch keine Kommentare
                                    </div>
                                ) : (
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', maxHeight: '200px', overflowY: 'auto' }}>
                                        {metrics.recentFeedback.filter(f => f.satisfaction_comment).map((f, i) => (
                                            <div key={i} style={{
                                                padding: '10px 14px',
                                                borderRadius: '8px',
                                                background: 'var(--bg-tertiary)',
                                                border: '1px solid var(--border-color)',
                                                borderLeft: `3px solid ${f.satisfaction_rating === 'gut' ? 'var(--success)' : 'var(--danger)'}`,
                                                fontSize: '0.8125rem',
                                            }}>
                                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '5px' }}>
                                                    <span style={{ display: 'flex', alignItems: 'center', gap: '6px', fontWeight: 600, color: 'var(--text-primary)' }}>
                                                        <span style={{ fontSize: '0.9rem' }}>{f.satisfaction_rating === 'gut' ? '👍' : '👎'}</span>
                                                        {f.requester_name || f.requester_email || '–'}
                                                    </span>
                                                    <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', fontFamily: 'monospace', background: 'var(--bg-secondary)', padding: '2px 6px', borderRadius: '4px' }}>
                                                        {f.ticket_number}
                                                    </span>
                                                </div>
                                                <div style={{ color: 'var(--text-secondary)', lineHeight: 1.5, fontSize: '0.8rem' }}>{f.satisfaction_comment}</div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}

                {/* Untere Reihe */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>

                    {/* Durchschnittliche Lösungszeit */}
                    <div className="card" style={{ padding: '20px 24px' }}>
                        <h3 style={{ margin: '0 0 16px', fontSize: '0.875rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-muted)' }}>
                            Ø Lösungszeit
                        </h3>
                        {metrics.avgResolution.length === 0 ? (
                            <div style={{ textAlign: 'center', padding: '1rem', color: 'var(--text-muted)', fontSize: '0.875rem' }}>Noch keine gelösten Tickets</div>
                        ) : (
                            metrics.avgResolution.map(r => (
                                <div key={r.priority} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px', padding: '8px 12px', background: 'var(--bg-tertiary)', borderRadius: '8px', border: `1px solid ${PRIO_COLOR[r.priority]}33` }}>
                                    <span style={{ fontSize: '0.8125rem', fontWeight: 600, color: PRIO_COLOR[r.priority] }}>
                                        {PRIO_LABEL[r.priority] || r.priority}
                                    </span>
                                    <div style={{ textAlign: 'right' }}>
                                        <div style={{ fontSize: '1rem', fontWeight: 800, color: 'var(--text-primary)' }}>
                                            {r.avg_hours !== null ? `${r.avg_hours}h` : '–'}
                                        </div>
                                        <div style={{ fontSize: '0.6875rem', color: 'var(--text-muted)' }}>{r.count} Tickets</div>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>

                    {/* Top-Bearbeiter */}
                    <div className="card" style={{ padding: '20px 24px' }}>
                        <h3 style={{ margin: '0 0 16px', fontSize: '0.875rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-muted)' }}>
                            Top-Bearbeiter
                        </h3>
                        {metrics.topAssignees.length === 0 ? (
                            <div style={{ textAlign: 'center', padding: '1rem', color: 'var(--text-muted)', fontSize: '0.875rem' }}>Keine zugewiesenen Tickets</div>
                        ) : (
                            metrics.topAssignees.map((a, i) => {
                                const name = a.first_name ? `${a.first_name} ${a.last_name || ''}`.trim() : a.username;
                                const initials = name.split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2);
                                const rate = a.total > 0 ? Math.round((a.resolved / a.total) * 100) : 0;
                                return (
                                    <div key={a.username} style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
                                        <span style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-muted)', width: '16px' }}>#{i + 1}</span>
                                        <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: 'linear-gradient(135deg, var(--cereda-primary), var(--cereda-accent))', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px', fontWeight: 700, color: 'white', flexShrink: 0 }}>
                                            {initials}
                                        </div>
                                        <div style={{ flex: 1 }}>
                                            <div style={{ fontSize: '0.8125rem', fontWeight: 600, color: 'var(--text-primary)' }}>{name}</div>
                                            <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>{a.resolved}/{a.total} gelöst ({rate}%)</div>
                                        </div>
                                    </div>
                                );
                            })
                        )}
                    </div>

                    {/* SLA-Verletzungen */}
                    <div className="card" style={{ padding: '20px 24px' }}>
                        <h3 style={{ margin: '0 0 16px', fontSize: '0.875rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-muted)' }}>
                            SLA-Verletzungen (offen)
                        </h3>
                        {metrics.slaBreaches.length === 0 ? (
                            <div style={{ textAlign: 'center', padding: '1rem' }}>
                                <div style={{ fontSize: '2rem', marginBottom: '8px' }}>✅</div>
                                <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)' }}>Keine SLA-Verletzungen!</div>
                            </div>
                        ) : (
                            metrics.slaBreaches.map(b => (
                                <div key={b.priority} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px', padding: '10px 12px', background: 'rgba(239,68,68,0.06)', borderRadius: '8px', border: '1px solid rgba(239,68,68,0.2)' }}>
                                    <span style={{ fontSize: '0.8125rem', fontWeight: 600, color: PRIO_COLOR[b.priority] }}>
                                        {PRIO_LABEL[b.priority] || b.priority}
                                    </span>
                                    <span style={{ fontSize: '1.125rem', fontWeight: 800, color: 'var(--danger)' }}>{b.count}</span>
                                </div>
                            ))
                        )}
                    </div>
                </div>

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

export default TicketMetricsPage;
