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

function LiveTimer({ startTime }) {
    const [elapsed, setElapsed] = useState('0:00');
    useEffect(() => {
        if (!startTime) return;
        // Backend naive UTC ISO gönderiyorsa parseUTC ile doğru çözülür,
        // yoksa LiveTimer 3 saatlik yanlış offset gösterirdi (TR için).
        const startObj = parseUTC(startTime);
        if (!startObj) return;
        const start = startObj.getTime();
        const tick = () => {
            const diff = Math.floor((Date.now() - start) / 1000);
            const m = Math.floor(diff / 60);
            const s = diff % 60;
            setElapsed(`${m}:${s.toString().padStart(2, '0')}`);
        };
        tick();
        const id = setInterval(tick, 1000);
        return () => clearInterval(id);
    }, [startTime]);
    return <span className="mono">{elapsed}</span>;
}

const SENTIMENT_STYLE = {
    positive: { bg: 'rgba(34,197,94,.07)',  border: 'rgba(34,197,94,.2)',  color: 'var(--green)' },
    neutral:  { bg: 'rgba(107,114,128,.06)', border: 'var(--border)',       color: 'var(--text-dim)' },
    negative: { bg: 'rgba(245,158,11,.07)', border: 'rgba(245,158,11,.2)', color: 'var(--amber)' },
    angry:    { bg: 'rgba(239,68,68,.07)',  border: 'rgba(239,68,68,.2)',  color: 'var(--red)' },
};

function SentimentBadge({ sentiment }) {
    if (!sentiment) return null;
    const s = SENTIMENT_STYLE[sentiment.label] || SENTIMENT_STYLE.neutral;
    return (
        <span title={`${sentiment.tr} (${sentiment.score}/100)`} style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '2px 8px', borderRadius: 6, fontSize: 12, fontWeight: 500,
            background: s.bg, border: `1px solid ${s.border}`, color: s.color,
            whiteSpace: 'nowrap',
        }}>
            {sentiment.tr}
        </span>
    );
}

function DashboardTab({ activeCalls, onTransfer, toast }) {
    const { data: stats } = window.useApi('/api/stats', [activeCalls.length]);

    // ── Son Çağrılar: filtre + sayfalama ─────────────────────────────────────
    const [calls, setCalls]           = useState([]);
    const [callsTotal, setCallsTotal] = useState(0);
    const [callsPages, setCallsPages] = useState(1);
    const [callsPage, setCallsPage]   = useState(1);
    const [filterPhone, setFilterPhone]   = useState('');
    const [filterStatus, setFilterStatus] = useState('');
    const [phoneInput, setPhoneInput]     = useState(''); // debounceable input
    const PER_PAGE = 10;

    const fetchCalls = useCallback(async () => {
        try {
            const params = new URLSearchParams({ page: callsPage, per_page: PER_PAGE });
            if (filterPhone)  params.set('phone',  filterPhone);
            if (filterStatus) params.set('status', filterStatus);
            const r = await authFetch(`/api/calls?${params}`);
            if (!r.ok) return;
            const data = await r.json();
            if (Array.isArray(data)) {
                setCalls(data);
                setCallsTotal(data.length);
                setCallsPages(1);
            } else {
                setCalls(data.calls || []);
                setCallsTotal(data.total || 0);
                setCallsPages(data.pages || 1);
            }
        } catch (_) {}
    }, [callsPage, filterPhone, filterStatus, activeCalls.length]);

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

    // Filtre değişince 1. sayfaya dön
    const applyFilter = useCallback(() => {
        setFilterPhone(phoneInput);
        setCallsPage(1);
    }, [phoneInput]);

    const resetFilters = useCallback(() => {
        setPhoneInput('');
        setFilterPhone('');
        setFilterStatus('');
        setCallsPage(1);
    }, []);

    const reloadCalls = fetchCalls;

    const [transcript, setTranscript]     = useState(null);
    const [transferCall, setTransferCall] = useState(null);
    const [sentimentMap, setSentimentMap] = useState({});

    const _EMOTION_META_FE = {
        positive: { emoji: '', tr: 'Olumlu' },
        neutral:  { emoji: '', tr: 'Nötr'   },
        negative: { emoji: '', tr: 'Olumsuz' },
        angry:    { emoji: '', tr: 'Sinirli' },
    };
    // ── Alarm Yönetimi ────────────────────────────────────────────────────────
    const [activeAlarms, setActiveAlarms]     = useState([]);

    // Sayfa açıldığında mevcut aktif alarmları API'den çek
    useEffect(() => {
        authFetch('/api/alarms/active')
            .then(r => r.ok ? r.json() : [])
            .then(data => setActiveAlarms(Array.isArray(data) ? data : []))
            .catch(() => {});
    }, []);

    // Alarm kapat
    const resolveAlarm = useCallback(async (alarm) => {
        try {
            await authFetch(`/api/alarms/${alarm.id}/resolve?resolved_by=supervisor`, { method: 'POST' });
        } catch (_) {}
        setActiveAlarms(prev => prev.filter(a => (a.id || a.call_uuid) !== (alarm.id || alarm.call_uuid)));
    }, []);

    // ── Dashboard WebSocket ───────────────────────────────────────────────────
    useEffect(() => {
        const proto = location.protocol === 'https:' ? 'wss' : 'ws';
        const ws = new WebSocket(`${proto}://${location.host}/ws/dashboard`);

        ws.onmessage = (e) => {
            try {
                const ev = JSON.parse(e.data);

                // Duygu güncelleme (mevcut)
                if (ev.type === 'sentiment_update') {
                    const { call_uuid, sentiment, text } = ev;
                    setSentimentMap(prev => ({ ...prev, [call_uuid]: sentiment }));
                    if (sentiment.label === 'angry' || sentiment.label === 'negative') {
                        const preview = text ? ` — "${text.slice(0, 60)}${text.length > 60 ? '…' : ''}"` : '';
                        toast(`${sentiment.emoji} ${ev.phone}: Müşteri ${sentiment.tr.toLowerCase()}${preview}`, sentiment.label === 'angry' ? 'error' : 'warning');
                    }
                }

                // ── YENİ: Alarm tetiklendi ────────────────────────────────────
                else if (ev.type === 'alarm_triggered') {
                    setActiveAlarms(prev => {
                        // Aynı çağrı + tip için son 10sn içinde eklenmişse tekrarlama
                        const now = Date.now();
                        const duplicate = prev.find(a => {
                            if (a.call_uuid !== ev.call_uuid || a.alarm_type !== ev.alarm_type) return false;
                            const t = parseUTC(a.triggered_at);
                            return t && (now - t.getTime() < 10000);
                        });
                        if (duplicate) return prev;
                        return [ev, ...prev];
                    });
                    // Ses çal
                    if (window.playAlarmSound) window.playAlarmSound();
                    // Toast bildirimi
                    const meta = {
                        angry_detected:     'Sinirli müşteri tespit edildi',
                        score_threshold:    'Yüksek olumsuzluk skoru',
                        sustained_negative: 'Sürekli olumsuz geri bildirim',
                        rapid_drop:         'Ani duygu düşüşü',
                    };
                    toast(meta[ev.alarm_type] || 'Duygu alarmı', 'error');
                }

                // ── Duygu iyileşti → alarmları otomatik kapat ────────────────
                else if (ev.type === 'alarm_resolved') {
                    setActiveAlarms(prev => prev.filter(a => a.call_uuid !== ev.call_uuid));
                    if (ev.auto) toast('Müşteri sakinleşti, alarmlar kapatıldı', 'success');
                }

                // Çağrı bitti — temizlik
                else if (ev.type === 'call_ended') {
                    setSentimentMap(prev => {
                        const next = { ...prev };
                        delete next[ev.call_uuid];
                        return next;
                    });
                    // Transkripti 30sn sonra temizle (son görüntüleme şansı)
                    setTimeout(() => {
                        setTranscriptMap(prev => {
                            const next = { ...prev };
                            delete next[ev.call_uuid];
                            return next;
                        });
                    }, 30000);
                    // Genişletilmiş kart kapandıysa sıfırla
                    setExpandedCall(prev => prev === ev.call_uuid ? null : prev);
                }

            } catch (_) {}
        };
        return () => ws.close();
    }, []);

    async function doTransfer(callUuid, dest) {
        const r = await authFetch('/api/transfer', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ call_uuid: callUuid, destination: dest })
        });
        const d = await r.json();
        if (d.ok) { toast('Transfer başarılı', 'success'); setTransferCall(null); reloadCalls(); }
        else toast('Transfer başarısız', 'error');
    }

    return (
        <div className="fade-in">

            {/* ── ALARM BANNER ─────────────────────────────────────────── */}
            {activeAlarms.length > 0 && (
                <div style={{ marginBottom: 8 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, color: '#ef4444', letterSpacing: '.04em' }}>
                            AKTİF ALARMLAR ({activeAlarms.length})
                        </span>
                        <div style={{ flex: 1, height: 1, background: 'rgba(239,68,68,.2)' }} />
                    </div>
                    <window.AlarmBanner alarms={activeAlarms} onResolve={resolveAlarm} />
                </div>
            )}

            {/* TOP STAT CARDS */}
            <div className="dash-stats">
                <div className="dash-stat-card">
                    <div className="dash-stat-icon" style={{ background: 'var(--blue-soft)', color: 'var(--blue)' }}>
                        <svg width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" 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-6 19.79 19.79 0 01-3.07-8.67A2 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>
                    </div>
                    <div className="dash-stat-content">
                        <div className="dash-stat-label">Aktif Çağrılar</div>
                        <div className="dash-stat-value">{activeCalls.length}</div>
                    </div>
                    {activeCalls.length > 0 && <div className="dash-stat-pulse" />}
                </div>
                <div className="dash-stat-card">
                    <div className="dash-stat-icon" style={{ background: 'var(--surface2)', color: 'var(--text-dim)' }}>
                        <svg width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2" ry="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>
                    </div>
                    <div className="dash-stat-content">
                        <div className="dash-stat-label">Bugün</div>
                        <div className="dash-stat-value">{stats?.today_calls ?? '—'}</div>
                    </div>
                </div>
                <div className="dash-stat-card">
                    <div className="dash-stat-icon" style={{ background: 'var(--surface2)', color: 'var(--text-dim)' }}>
                        <svg width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                    </div>
                    <div className="dash-stat-content">
                        <div className="dash-stat-label">Ort. Süre</div>
                        <div className="dash-stat-value">{stats ? window.fmtDuration(stats.avg_duration) : '—'}</div>
                    </div>
                </div>
                <div className="dash-stat-card">
                    <div className="dash-stat-icon" style={{ background: 'var(--surface2)', color: 'var(--text-dim)' }}>
                        <svg width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" 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>
                    </div>
                    <div className="dash-stat-content">
                        <div className="dash-stat-label">Transfer</div>
                        <div className="dash-stat-value">{stats?.transferred_calls ?? '—'}</div>
                    </div>
                </div>
                <div className="dash-stat-card">
                    <div className="dash-stat-icon" style={{ background: 'var(--surface2)', color: 'var(--text-dim)' }}>
                        <svg width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4-4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87"/><path d="M16 3.13a4 4 0 010 7.75"/></svg>
                    </div>
                    <div className="dash-stat-content">
                        <div className="dash-stat-label">Toplam</div>
                        <div className="dash-stat-value">{stats?.total_calls ?? '—'}</div>
                    </div>
                </div>
            </div>

            {/* MAIN GRID: Live AI Calls + Charts */}
            <div className="dash-grid">
                <div className="panel dash-live">
                    <div className="panel-header">
                        <span className="panel-title" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            {activeCalls.length > 0 && <span className="live-dot" />} AI Canlı Çağrılar
                        </span>
                        <span className="dash-count-badge">{activeCalls.length}</span>
                    </div>
                    <div className="dash-live-body">
                        {activeCalls.length === 0 ? (
                            <div className="dash-empty">
                                <div style={{ fontSize: 14, color: 'var(--text-dim)', fontWeight: 500 }}>Aktif yapay zeka çağrısı yok</div>
                            </div>
                        ) : (
                            activeCalls.map(c => {
                            const sentiment   = sentimentMap[c.call_uuid];
                            const isAlert     = sentiment?.label === 'angry' || sentiment?.label === 'negative';
                            const hasAlarm    = activeAlarms.some(a => a.call_uuid === c.call_uuid);

                            return (
                                <div key={c.call_uuid} className="dash-live-card" style={{
                                    borderLeft: hasAlarm
                                        ? '3px solid #ef4444'
                                        : isAlert
                                            ? `3px solid ${sentiment.label === 'angry' ? 'var(--red)' : 'var(--amber)'}`
                                            : undefined,
                                    flexDirection: 'column',
                                    padding: '12px 16px',
                                }}>
                                    {/* Üst satır: avatar + bilgi + butonlar */}
                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                                        <div className="dash-live-left">
                                            <div className="dash-live-avatar" style={{ position: 'relative' }}>
                                                {hasAlarm && (
                                                    <span style={{
                                                        position: 'absolute', top: -4, right: -4,
                                                        width: 10, height: 10, borderRadius: '50%',
                                                        background: '#ef4444',
                                                        boxShadow: '0 0 0 2px var(--surface), 0 0 6px #ef4444',
                                                        animation: 'pulse 1.2s infinite',
                                                    }} />
                                                )}
                                                {(sentiment?.tr || c.agent_name || 'AI').substring(0, 2).toUpperCase()}
                                            </div>
                                            <div>
                                                <div className="mono" style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{c.phone_number}</div>
                                                <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                                                    {c.agent_name}
                                                    {sentiment && <SentimentBadge sentiment={sentiment} />}
                                                </div>
                                            </div>
                                        </div>
                                        <div className="dash-live-right" style={{ gap: 6 }}>
                                            <div className="dash-live-meta">
                                                <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>{c.message_count} msg</span>
                                                <span className="dash-live-timer"><LiveTimer startTime={c.start_time} /></span>
                                            </div>
                                            <button className="btn-sm" style={{ fontSize: 12, padding: '4px 10px', color: 'var(--amber)', borderColor: 'rgba(245,158,11,.3)' }} onClick={() => setTransferCall(c)}>Transfer</button>
                                        </div>
                                    </div>

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

                <div className="panel dash-chart">
                    <div className="panel-header"><span className="panel-title">Haftalık Çağrı Trendi</span></div>
                    <div style={{ padding: '16px 16px 8px', height: 360 }}>
                        {stats?.daily_calls?.length > 0 ? (
                            <ResponsiveContainer width="100%" height="100%">
                                <AreaChart data={stats.daily_calls} margin={{ top: 4, right: 4, left: -20, bottom: 0 }}>
                                    <defs>
                                        <linearGradient id="colorCalls" x1="0" y1="0" x2="0" y2="1">
                                            <stop offset="0%" stopColor="#3b6df0" stopOpacity={0.2} />
                                            <stop offset="95%" stopColor="#3b6df0" stopOpacity={0} />
                                        </linearGradient>
                                    </defs>
                                    <XAxis dataKey="date" tick={{ fontSize: 11, fill: '#94a3b8' }} tickFormatter={v => v.slice(5)} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false} allowDecimals={false} />
                                    <Tooltip contentStyle={{ borderRadius: 10, fontSize: 13 }} />
                                    <Area type="monotone" dataKey="count" stroke="#3b6df0" strokeWidth={2.5} fill="url(#colorCalls)" />
                                </AreaChart>
                            </ResponsiveContainer>
                        ) : <div className="dash-empty" style={{ height: '100%' }}>Veri yok</div>}
                    </div>
                </div>

            </div>

            {transcript && <window.TranscriptModal callId={transcript} onClose={() => setTranscript(null)} />}
            {transferCall && <window.TransferModal call={transferCall} onClose={() => setTransferCall(null)} onTransfer={doTransfer} />}
        </div>
    );
}

window.DashboardTab = DashboardTab;