const { useState, useEffect, useMemo } = React;
const {
    ResponsiveContainer, AreaChart, Area, BarChart, Bar,
    XAxis, YAxis, Tooltip, CartesianGrid, Cell
} = Recharts;

/* ═══════════════════════════════════════════════════════════════
   STATS TAB — Tam Yeniden Tasarım
   ═══════════════════════════════════════════════════════════════ */

/* ── Mini KPI Kartı ── */
function KpiCard({ icon, label, value, sub, color, trend }) {
    const trendUp = trend > 0;
    const trendColor = trendUp ? '#22c55e' : trend < 0 ? '#ef4444' : 'var(--text-dim)';
    return (
        <div className="stats-kpi">
            <div className="stats-kpi-icon" style={{ background: `${color}14`, color }}>
                {icon}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
                <div className="stats-kpi-label">{label}</div>
                <div className="stats-kpi-value">{value}</div>
            </div>
            {trend !== undefined && trend !== null && (
                <div style={{ fontSize: 12, fontWeight:600, color: trendColor, display: 'flex', alignItems: 'center', gap: 2 }}>
                    <span style={{ fontSize: 14 }}>{trendUp ? '↑' : trend < 0 ? '↓' : '→'}</span>
                    {Math.abs(trend)}%
                </div>
            )}
            {sub && !trend && trend !== 0 && <div className="stats-kpi-sub">{sub}</div>}
        </div>
    );
}

/* ── Saatlik Isı Haritası ── */
function HourlyHeatmap({ data }) {
    const maxCount = Math.max(...data.map(d =>d.count), 1);
    return (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 4 }}>
            {data.map(d => {
                const intensity = d.count / maxCount;
                const bg = d.count === 0
                    ? 'var(--surface2)'
                    : `rgba(59, 109, 240, ${0.12 + intensity * 0.78})`;
                const textColor = intensity > 0.5 ? '#fff' : 'var(--text-dim)';
                return (
                    <div key={d.hour} title={`${d.hour}:00 — ${d.count} çağrı`}
                        style={{
                            padding: '8px 0', borderRadius: 6, textAlign: 'center',
                            background: bg, color: textColor, fontSize: 11, fontWeight:600,
                            fontFamily: 'var(--mono)', cursor: 'default',
                            transition: 'all .2s ease', position: 'relative',
                        }}>
                        <div style={{ fontSize: 10, opacity: .7, marginBottom: 2 }}>{String(d.hour).padStart(2, '0')}</div>
                        <div>{d.count}</div>
                    </div>
                );
            })}
        </div>
    );
}

/* ── Durum Çubuğu ── */
function StatusBar({ data, total }) {
    const statusConfig = {
        ended: { label: 'Tamamlanan', color: '#22c55e' },
        transferred: { label: 'Transfer', color: '#06b6d4' },
        active: { label: 'Aktif', color: '#f59e0b' },
        abandoned: { label: 'Terk Edilen', color: '#ef4444' },
        failed: { label: 'Başarısız', color: '#ef4444' },
    };
    if (!data || data.length === 0 || total === 0) return null;

    return (
        <div>
            <div style={{ display: 'flex', borderRadius: 8, overflow: 'hidden', height: 28, marginBottom: 14 }}>
                {data.map(d => {
                    const cfg = statusConfig[d.status] || { label: d.status, color: '#94a3b8' };
                    const pct = (d.count / total * 100);
                    if (pct < 1) return null;
                    return (
                        <div key={d.status} title={`${cfg.label}: ${d.count} (${pct.toFixed(1)}%)`}
                            style={{
                                width: `${pct}%`, background: cfg.color, minWidth: pct > 3 ? 'auto' : 4,
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                fontSize: 11, fontWeight:600, color: '#fff',
                                transition: 'width .5s ease',
                            }}>
                            {pct > 10 && `${Math.round(pct)}%`}
                        </div>
                    );
                })}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px 20px' }}>
                {data.map(d => {
                    const cfg = statusConfig[d.status] || { label: d.status, color: '#94a3b8' };
                    return (
                        <div key={d.status} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <span style={{ width: 8, height: 8, borderRadius: '50%', background: cfg.color }} />
                            <span style={{ fontSize: 13, color: 'var(--text-dim)', fontWeight: 600 }}>{cfg.label}</span>
                            <span className="mono" style={{ fontSize: 13, fontWeight:600, color: 'var(--text)' }}>{d.count}</span>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}

/* ── Özel Tooltip ── */
function ChartTooltip({ active, payload, label, suffix }) {
    if (!active || !payload?.length) return null;
    return (
        <div style={{
            background: 'var(--surface-solid)', border: '1px solid var(--border)', borderRadius: 10,
            padding: '10px 14px', boxShadow: 'var(--shadow-md)', fontSize: 13,
        }}>
            <div style={{ fontWeight:600, color: 'var(--text)', marginBottom: 4 }}>{label}</div>
            {payload.map((p, i) => (
                <div key={i} style={{ color: p.color || 'var(--blue)', fontWeight: 600 }}>
                    {p.value} {suffix || 'çağrı'}
                </div>
            ))}
        </div>
    );
}


/* ═══ ANA COMPONENT ═══ */
function StatsTab() {
    const { data: stats, loading } = window.useApi('/api/stats', []);
    const { data: qcSessionsData } = window.useApi('/api/qc/sessions?limit=100', []);
    const [period, setPeriod] = useState('14d');

    const daily = useMemo(() => {
        if (!stats?.daily_calls) return [];
        const days = period === '7d' ? 7 : 14;
        return stats.daily_calls.slice(-days).map(d => ({
            ...d,
            label: d.date.slice(5),
        }));
    }, [stats, period]);

    const qcStats = useMemo(() => {
        // API artık {total, items, ...} formatında döndürüyor
        const qcSessions = Array.isArray(qcSessionsData) ? qcSessionsData : (qcSessionsData?.items || []);
        if (!qcSessions || qcSessions.length === 0) return null;
        const total = qcSessions.length;
        const completed = qcSessions.filter(s => s.status === 'completed').length;
        const failed = qcSessions.filter(s => s.status === 'failed').length;
        const abandoned = qcSessions.filter(s => s.status === 'abandoned').length;
        return { total, completed, failed, abandoned, rate: total > 0 ? Math.round(completed / total * 100) : 0 };
    }, [qcSessionsData]);

    if (loading || !stats) {
        return (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 400 }}>
                <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: 15, color: 'var(--text-dim)', fontWeight: 600 }}>Raporlar yükleniyor...</div>
                </div>
            </div>
        );
    }

    const durBucketColors = ['#e2e8f0', '#bfdbfe', '#93c5fd', '#60a5fa', '#3b82f6', '#1d4ed8'];

    return (
        <div className="fade-in">
            {/* ═══ BAŞLIK ═══ */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
                <div>
                    <h2 style={{ fontSize: 22, fontWeight:600, color: 'var(--text)', margin: 0 }}>Raporlar & Analiz</h2>
                    <p style={{ fontSize: 13, color: 'var(--text-dim)', fontWeight: 500, marginTop: 4 }}>Çağrı merkezi performansınızın detaylı görünümü</p>
                </div>
                <div style={{ display: 'flex', gap: 4, background: 'var(--surface2)', padding: 3, borderRadius: 10 }}>
                    {[{ k: '7d', l: '7 Gün' }, { k: '14d', l: '14 Gün' }].map(p => (
                        <button key={p.k} onClick={() =>setPeriod(p.k)}
                            style={{
                                padding: '6px 14px', border: 'none', borderRadius: 8,
                                fontSize: 13, fontWeight:600, cursor: 'pointer',
                                fontFamily: 'var(--font)',
                                background: period === p.k ? 'var(--surface)' : 'transparent',
                                color: period === p.k ? 'var(--text)' : 'var(--text-dim)',
                                boxShadow: period === p.k ? 'var(--shadow-sm)' : 'none',
                                transition: 'all .15s ease',
                            }}>{p.l}</button>
                    ))}
                </div>
            </div>

            {/* ═══ KPI KARTLARI ═══ */}
            <div className="stats-kpi-grid">
                <KpiCard
                    icon={<svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6A19.79 19.79 0 012.12 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/></svg>}
                    label="Toplam Çağrı" value={stats.total_calls} color="#3b6df0"
                    trend={stats.week_change}
                />
                <KpiCard
                    icon={<svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>}
                    label="Bugün" value={stats.today_calls} color="#06b6d4"
                    sub={`Dün: ${stats.yesterday_calls}`}
                />
                <KpiCard
                    icon={<svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>}
                    label="Ort. Süre" value={window.fmtDuration(stats.avg_duration)} color="#f59e0b"
                    sub={`Max: ${window.fmtDuration(stats.max_duration)}`}
                />
                <KpiCard
                    icon={<svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>}
                    label="Transfer Oranı"
                    value={stats.total_calls > 0 ? `%${Math.round(stats.transferred_calls / stats.total_calls * 100)}` : '%0'}
                    color="#8b5cf6"
                    sub={`${stats.transferred_calls} çağrı`}
                />
                {qcStats && (
                    <KpiCard
                        icon={<svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>}
                        label="QC Başarı" value={`%${qcStats.rate}`} color="#22c55e"
                        sub={`${qcStats.completed}/${qcStats.total} tamamlandı`}
                    />
                )}
            </div>

            {/* ═══ ANA GRAFİKLER ═══ */}
            <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 20, marginBottom: 20 }}>
                {/* Çağrı Trendi */}
                <div className="panel">
                    <div className="panel-header">
                        <span className="panel-title">Çağrı Trendi</span>
                        <span style={{ fontSize: 13, fontWeight:600, color: 'var(--blue)', fontFamily: 'var(--mono)' }}>
                            {stats.this_week_calls} bu hafta
                        </span>
                    </div>
                    <div style={{ padding: '20px 16px 8px', height: 280 }}>
                        {daily.length > 0 ? (
                            <ResponsiveContainer width="100%" height="100%">
                                <AreaChart data={daily} margin={{ top: 4, right: 4, left: -20, bottom: 0 }}>
                                    <defs>
                                        <linearGradient id="statsGrad" x1="0" y1="0" x2="0" y2="1">
                                            <stop offset="0%" stopColor="#3b6df0" stopOpacity={0.15} />
                                            <stop offset="100%" stopColor="#3b6df0" stopOpacity={0} />
                                        </linearGradient>
                                    </defs>
                                    <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
                                    <XAxis dataKey="label" tick={{ fontSize: 11, fill: '#94a3b8', fontFamily: 'Space Mono' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false} allowDecimals={false} />
                                    <Tooltip content={<ChartTooltip />} />
                                    <Area type="monotone" dataKey="count" stroke="#3b6df0" strokeWidth={2.5} fill="url(#statsGrad)" dot={{ r: 3, fill: '#3b6df0', strokeWidth: 0 }} activeDot={{ r: 5, fill: '#3b6df0', stroke: '#fff', strokeWidth: 2 }} />
                                </AreaChart>
                            </ResponsiveContainer>
                        ) : (
                            <div className="dash-empty" style={{ height: '100%' }}><div style={{ fontSize: 13, color: 'var(--text-dim)' }}>Veri yok</div></div>
                        )}
                    </div>
                </div>

                {/* Durum Dağılımı + Süre */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <div className="panel" style={{ flex: 1 }}>
                        <div className="panel-header"><span className="panel-title">Çağrı Durumları</span></div>
                        <div style={{ padding: 20 }}>
                            <StatusBar data={stats.status_distribution} total={stats.total_calls} />
                        </div>
                    </div>
                    <div className="panel" style={{ flex: 1 }}>
                        <div className="panel-header"><span className="panel-title">Süre Dağılımı</span></div>
                        <div style={{ padding: '16px 16px 8px', height: 160 }}>
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={stats.duration_distribution} barSize={28}>
                                    <XAxis dataKey="range" tick={{ fontSize: 10, fill: '#94a3b8', fontFamily: 'Space Mono' }} axisLine={false} tickLine={false} />
                                    <YAxis hide />
                                    <Tooltip content={<ChartTooltip suffix="çağrı" />} />
                                    <Bar dataKey="count" radius={[4, 4, 0, 0]}>
                                        {stats.duration_distribution.map((_, i) => (
                                            <Cell key={i} fill={durBucketColors[i]} />
                                        ))}
                                    </Bar>
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>
                </div>
            </div>

            {/* ═══ İKİNCİ SATIR ═══ */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
                {/* Saatlik Dağılım */}
                <div className="panel">
                    <div className="panel-header">
                        <span className="panel-title">Saatlik Yoğunluk</span>
                        <span style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 600 }}>Son 7 gün</span>
                    </div>
                    <div style={{ padding: 20 }}>
                        {stats.hourly_distribution ? (
                            <HourlyHeatmap data={stats.hourly_distribution} />
                        ) : (
                            <div className="no-data">Veri yok</div>
                        )}
                    </div>
                </div>

                {/* QC Sonuçları */}
                <div className="panel">
                    <div className="panel-header">
                        <span className="panel-title">Kalite Kontrol Özeti</span>
                        {qcStats && <span style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 600 }}>{qcStats.total} değerlendirme</span>}
                    </div>
                    <div style={{ padding: 20 }}>
                        {qcStats ? (
                            <div>
                                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 16 }}>
                                    {[
                                        { label: 'Başarılı', value: qcStats.completed, color: '#22c55e' },
                                        { label: 'Başarısız', value: qcStats.failed, color: '#ef4444' },
                                        { label: 'Terk Edilen', value: qcStats.abandoned, color: '#f59e0b' },
                                    ].map(s => (
                                        <div key={s.label} style={{ textAlign: 'center', padding: 14, background: 'var(--surface2)', borderRadius: 10 }}>
                                            <div className="mono" style={{ fontSize: 24, fontWeight:600, color: s.color }}>{s.value}</div>
                                            <div style={{ fontSize: 11, fontWeight:600, color: 'var(--text-dim)', marginTop: 4, textTransform: 'uppercase', letterSpacing: '.03em' }}>{s.label}</div>
                                        </div>
                                    ))}
                                </div>
                                {/* Başarı çubuğu */}
                                <div style={{ background: 'var(--surface2)', borderRadius: 6, height: 10, overflow: 'hidden' }}>
                                    <div style={{
                                        width: `${qcStats.rate}%`, height: '100%', borderRadius: 6,
                                        background: 'linear-gradient(90deg, #22c55e, #16a34a)',
                                        transition: 'width .6s ease',
                                    }} />
                                </div>
                                <div style={{ textAlign: 'center', marginTop: 8, fontSize: 13, fontWeight:600, color: 'var(--text-dim)' }}>
                                    Başarı oranı: <span style={{ color: '#22c55e' }}>%{qcStats.rate}</span>
                                </div>
                            </div>
                        ) : (
                            <div className="dash-empty">
                                <div style={{ fontSize: 13, color: 'var(--text-dim)', fontWeight: 600 }}>Henüz QC verisi yok</div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* ═══ AGENT PERFORMANSI ═══ */}
            {stats.agent_performance?.length > 0 && (
                <div className="panel" style={{ marginBottom: 20 }}>
                    <div className="panel-header">
                        <span className="panel-title">Asistan Performansı</span>
                    </div>
                    <div style={{ overflowX: 'auto' }}>
                        <table className="dash-table">
                            <thead>
                                <tr>
                                    <th>Asistan</th>
                                    <th>Toplam Çağrı</th>
                                    <th>Tamamlanan</th>
                                    <th>Transfer</th>
                                    <th>Ort. Süre</th>
                                    <th>Dağılım</th>
                                </tr>
                            </thead>
                            <tbody>
                                {stats.agent_performance.map(a => {
                                    const maxTotal = stats.agent_performance[0]?.total || 1;
                                    const barPct = (a.total / maxTotal * 100);
                                    return (
                                        <tr key={a.name}>
                                            <td><span style={{ fontWeight:600, fontSize: 14 }}>{a.name}</span></td>
                                            <td><span className="mono" style={{ fontWeight:600, fontSize: 15 }}>{a.total}</span></td>
                                            <td><span className="mono" style={{ fontWeight:600, color: '#22c55e' }}>{a.ended}</span></td>
                                            <td><span className="mono" style={{ fontWeight:600, color: '#06b6d4' }}>{a.transferred}</span></td>
                                            <td><span className="mono" style={{ fontWeight:600, fontSize: 13 }}>{window.fmtDuration(a.avg_duration)}</span></td>
                                            <td style={{ width: 180 }}>
                                                <div style={{ height: 8, borderRadius: 4, background: 'var(--surface2)', overflow: 'hidden' }}>
                                                    <div style={{
                                                        width: `${barPct}%`, height: '100%', borderRadius: 4,
                                                        background: 'linear-gradient(90deg, #3b6df0, #60a5fa)',
                                                        transition: 'width .5s ease',
                                                    }} />
                                                </div>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {/* ═══ DEPARTMAN DAĞILIMI ═══ */}
            {stats.department_distribution?.length > 0 && (
                <div className="panel">
                    <div className="panel-header">
                        <span className="panel-title">Departman Dağılımı</span>
                    </div>
                    <div style={{ padding: 24 }}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                            {stats.department_distribution.map((d, i) => {
                                const colors = { support: '#3b6df0', sales: '#22c55e', appointment: '#8b5cf6' };
                                const labels = { support: 'Destek', sales: 'Satış', appointment: 'Randevu' };
                                const color = colors[d.dept] || '#94a3b8';
                                const pct = stats.total_calls > 0 ? Math.round(d.count / stats.total_calls * 100) : 0;
                                return (
                                    <div key={d.dept}>
                                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                                <span style={{ width: 10, height: 10, borderRadius: '50%', background: color }} />
                                                <span style={{ fontSize: 14, fontWeight:600, color: 'var(--text)' }}>{labels[d.dept] || d.dept}</span>
                                            </div>
                                            <span className="mono" style={{ fontSize: 14, fontWeight:600, color }}>
                                                {d.count} <span style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 500 }}>%{pct}</span>
                                            </span>
                                        </div>
                                        <div style={{ height: 8, borderRadius: 4, background: 'var(--surface2)' }}>
                                            <div style={{
                                                width: `${pct}%`, height: '100%', borderRadius: 4, background: color,
                                                transition: 'width .6s cubic-bezier(.4,0,.2,1)',
                                            }} />
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

window.StatsTab = StatsTab;
