@extends('layouts.app')

@section('title', 'AI Analytics & Log System')

@section('content')
    <div class="bg-gray-50 min-h-screen pb-12">

        <div class="h-56 bg-gradient-to-r from-blue-900 via-blue-700 to-blue-500 rounded-b-[2.5rem]"></div>

        <div class="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 -mt-36">

            <div class="text-white mb-10">
                <h1 class="text-3xl md:text-4xl font-extrabold">📊 Dashboard Analisis Chatbot</h1>
                <p class="text-blue-100 mt-2">Menampilkan kualitas jawaban chatbot berdasarkan pertanyaan pengguna</p>
            </div>
            <div class="bg-white p-4 rounded-xl shadow mb-6 text-sm text-gray-600">
                <p class="font-semibold mb-1">📌 Keterangan:</p>
                <ul class="list-disc ml-5 space-y-1">
                    <li><b>Total Pertanyaan</b>: jumlah semua pertanyaan dari pengguna</li>
                    <li><b>Jawaban Benar</b>: persentase jawaban yang sesuai dengan pertanyaan</li>
                    <li><b>Jawaban Tidak Sesua</b>: jawaban yang kurang tepat atau tidak relevan</li>
                    <li><b>Penilaian Admin</b>: hasil pengecekan manual oleh admin</li>
                </ul>
            </div>
            <div class="grid grid-cols-2 md:grid-cols-5 gap-6 mb-10">

                <div class="bg-white p-6 rounded-2xl shadow border text-center">
                    <p class="text-xs text-gray-500 uppercase">Total Pertanyaan</p>
                    <p class="text-3xl font-bold text-gray-800">{{ $totalChats }}</p>
                </div>

                <div class="bg-white p-6 rounded-2xl shadow border text-center">
                    <p class="text-xs text-gray-500 uppercase">Jawaban Benar</p>
                    <p class="text-3xl font-bold text-green-600">{{ round($successRate) }}%</p>
                </div>

                <div class="bg-white p-6 rounded-2xl shadow border text-center">
                    <p class="text-xs text-gray-500 uppercase">Tidak Terjawab</p>
                    <p class="text-3xl font-bold text-red-500"> {{ round($notAnsweredRate) }}%</p>
                </div>

                <div class="bg-white p-6 rounded-2xl shadow border text-center">
                    <p class="text-xs text-gray-500 uppercase">Accuracy (Hasil Evaluasi Admin)</p>
                    <p class="text-3xl font-bold text-blue-600">{{ round($accuracy) }}%</p>
                </div>
                <div class="bg-white p-6 rounded-2xl shadow border text-center">
                    <p>Jawaban Tidak Sesuai</p>
                    <p class="text-3xl font-bold text-orange-500">
                        {{ round($notSuitableRate) }}%
                    </p>
                </div>

            </div>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-10">

                <div class="bg-white rounded-2xl shadow p-6 flex flex-col items-center justify-center">

                    <h3 class="text-sm font-semibold mb-4 text-gray-600">Perbandingan Hasil Jawaban Chatbot</h3>

                    <div class="w-52 h-52 relative">
                        <canvas id="chart"></canvas>

                    </div>

                    <p class="text-xs text-gray-400 mt-2 text-center">
                        Grafik ini menunjukkan perbandingan kualitas jawaban chatbot berdasarkan
                        {{ $validContext + $knowledgeGap + $outOfContext }} data evaluasi
                    </p>


                </div>

                <div class="bg-white rounded-2xl shadow p-6">

                    <h3 class="text-sm font-semibold mb-4 text-gray-600">Trend Performa</h3>

                    <canvas id="trendChart" height="120"></canvas>

                </div>

            </div>

            <p class="text-xs text-gray-500 mb-2">
                Pilih kategori untuk melihat jenis jawaban chatbot
            </p>
            <div class="mb-4 flex gap-3 flex-wrap">

                <a href="?filter=all"
                    class="px-4 py-2 rounded-xl text-sm font-medium transition
{{ $filter == 'all' ? 'bg-slate-800 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' }}">
                    Semua ({{ $totalChats }})
                </a>

                <a href="?filter=pending"
                    class="px-4 py-2 rounded-xl text-sm font-medium transition
{{ $filter == 'pending' ? 'bg-orange-500 text-white' : 'bg-orange-100 text-orange-800 hover:bg-orange-200' }}">
                    ⏳ Perlu Dicek ({{ $pendingCount }})
                </a>

                <a href="?filter=valid"
                    class="px-4 py-2 rounded-xl text-sm font-medium transition
        {{ $filter == 'valid' ? 'bg-green-600 text-white' : 'bg-green-100 text-green-700 hover:bg-green-200' }}">
                    ✔ Jawaban Benar ({{ $validCount }})
                </a>

                <a href="?filter=gap" class="px-4 py-2 rounded-xl text-sm font-medium transition"
                    style="{{ $filter == 'gap' ? 'background-color:#f59e0b; color:white;' : 'background-color:#fef3c7; color:#92400e;' }}"
                    onmouseover="this.style.backgroundColor='#fde68a'"
                    onmouseout="this.style.backgroundColor='{{ $filter == 'gap' ? '#f59e0b' : '#fef3c7' }}'">
                    ⚠ Kurang Tepat ({{ $gapCount }})
                </a>

                <a href="?filter=auto"
                    class="px-4 py-2 rounded-xl text-sm font-medium transition
{{ $filter == 'auto' ? 'bg-red-600 text-white' : 'bg-red-100 text-red-700 hover:bg-red-200' }}">
                    ❌ Tidak Ada Jawaban ({{ $autoCount }})
                </a>
            </div>

            <!-- FILTER SCORE -->
            <div class="mb-6 flex gap-3 flex-wrap">

                <a href="?filter=high"
                    class="px-4 py-2 rounded-xl text-sm font-medium transition
        {{ $filter == 'high' ? 'bg-blue-600 text-white' : 'bg-blue-100 text-blue-700 hover:bg-blue-200' }}">
                    High Score ({{ $highScore }})
                </a>

                <a href="?filter=medium"
                    class="px-4 py-2 rounded-xl text-sm font-medium transition
        {{ $filter == 'medium' ? 'bg-purple-600 text-white' : 'bg-purple-100 text-purple-700 hover:bg-purple-200' }}">
                    Medium Score ({{ $mediumScore }})
                </a>

                <a href="?filter=low"
                    class="px-4 py-2 rounded-xl text-sm font-medium transition
   @if (request('filter') == 'low') bg-cyan-600 text-white
   @else
       bg-cyan-100 text-cyan-800 hover:bg-cyan-200 @endif">
                    Low Score ({{ $lowScore }})
                </a>

            </div>
            @if ($pendingCount > 0)
                <div class="mb-4 p-3 bg-yellow-100 text-yellow-700 rounded-lg text-sm">
                    ⚠️ Ada {{ $pendingCount }} Jawaban chatbot yang perlu dicek karena belum dipastikan benar atau tidak
                </div>
            @endif
            <!-- TABLE -->
            <div class="bg-white rounded-2xl shadow border overflow-hidden">
                <table class="w-full text-sm">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="p-4">Waktu</th>
                            <th class="p-4">Pertanyaan</th>
                            <th class="p-4 text-center">Score</th>
                            <th class="p-4">Jawaban</th>
                            <th class="p-4 text-center">Status</th>
                            <th class="p-4 text-center">Validasi</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach ($chats as $chat)
                            <tr class="border-t">

                                <td class="p-4 text-xs">
                                    {{ $chat->created_at }}
                                </td>

                                <td class="p-4">
                                    {{ $chat->user_message }}
                                </td>

                                <td class="p-4 text-center">
                                    @php
                                        $isOutOfContext = $chat->similarity_score < 0.5;
                                    @endphp

                                    <div
                                        class="font-mono text-xs font-bold px-2 py-1 rounded mb-1 
        {{ $isOutOfContext ? 'bg-orange-50 text-orange-600' : 'bg-emerald-50 text-emerald-600' }}">

                                        {{ number_format($chat->similarity_score, 2) }}
                                    </div>

                                    @if ($chat->query_vector)
                                        <button onclick="openVectorModal('{{ $chat->id }}')"
                                            class="text-xs bg-slate-800 text-white px-3 py-1.5 rounded-lg hover:bg-slate-700 transition w-full flex items-center justify-center gap-1">
                                            📊 Analisis (Vector)
                                        </button>

                                        <div id="vector-data-{{ $chat->id }}" class="hidden">
                                            {{ $chat->query_vector }}
                                        </div>
                                    @endif
                                </td>

                                <td class="p-4 text-xs">
                                    {{ Str::limit($chat->bot_response, 80) }}

                                    <button data-text='@json($chat->bot_response)' onclick="openModal(this.dataset.text)"
                                        class="text-blue-500 text-xs underline ml-2">
                                        Lihat Detail
                                    </button>

                                    @if ($chat->doc_scores)
                                        <button onclick="openDocScore('{{ $chat->id }}')"
                                            class="text-indigo-500 text-xs underline ml-2">
                                            Lihat Relevansi
                                        </button>

                                        <div id="doc-score-{{ $chat->id }}" class="hidden">
                                            {{ $chat->doc_scores }}
                                        </div>
                                    @endif
                                </td>

                        
                                <td class="p-4 text-center">
                                    @php
                                        $isAuto = str_contains(strtolower($chat->bot_response), 'maaf');
                                    @endphp

                                    @if ($isAuto)
                                        <span class="text-gray-400 text-xs font-bold">Auto</span>
                                    @elseif($chat->is_correct === true)
                                        <span class="text-green-600 text-xs font-bold">✔ Valid</span>
                                    @elseif($chat->is_correct === false)
                                        <span class="text-red-500 text-xs font-bold">✖ Jawaban Tidak Sesuai</span>
                                    @else
                                        <span class="text-yellow-500 text-xs">Pending</span>
                                    @endif
                                </td>

                        
                                <td class="p-4 text-center">

                                    @php
                                        $isAuto = str_contains(strtolower($chat->bot_response), 'maaf');
                                    @endphp

                                    @if ($isAuto)
                                        <span class="text-gray-400 text-xs">Auto</span>
                                    @elseif($chat->is_correct === true)
                                        <span class="text-green-600 text-xs font-bold">✔</span>
                                    @elseif($chat->is_correct === false)
                                        <span class="text-red-600 text-xs font-bold">✖</span>
                                    @else
                                        <form action="{{ route('admin.chatlog.validate', $chat->id) }}" method="POST"
                                            class="flex gap-1 justify-center">
                                            @csrf
                                            <button type="submit" name="is_correct" value="1"
                                                class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded">✔</button>
                                            <button type="submit" name="is_correct" value="0"
                                                class="px-2 py-1 bg-red-100 text-red-700 text-xs rounded">✖</button>
                                        </form>
                                    @endif

                                </td>

                            </tr>
                        @endforeach
                    </tbody>
                </table>
                <div class="mt-6">
                    {{ $chats->appends(['filter' => $filter])->links() }}
                </div>

            </div>
            <div id="modal" class="fixed top-0 left-0 w-full min-h-full bg-black bg-opacity-50 hidden z-50">
                <div class="flex items-start justify-center min-h-screen p-6">
                    <div class="bg-white p-6 rounded-xl max-w-lg w-full">

                        <h2 class="text-lg font-bold mb-3">Jawaban Lengkap</h2>
                        <p class="text-xs text-gray-400 mb-2">
                            Berikut adalah jawaban lengkap dari chatbot
                        </p>
                        <div id="modalText" class="text-sm text-gray-700"></div>

                        <div class="mt-4 text-right">
                            <button onclick="closeModal()" class="px-4 py-2 bg-gray-600 text-white rounded">
                                Tutup
                            </button>
                        </div>

                    </div>
                </div>
            </div>
            <div id="vectorModal"
                class="fixed inset-0 w-full min-h-screen bg-slate-900 bg-opacity-90 hidden z-[60] flex items-center justify-center p-4 backdrop-blur-sm transition-opacity">
                <div class="bg-[#0f172a] border border-slate-700 p-6 rounded-xl max-w-4xl w-full shadow-2xl">

                    <div class="flex justify-between items-center mb-4 border-b border-slate-700 pb-3">
                        <div>
                            <h2 class="text-xl font-bold text-emerald-400 font-mono flex items-center gap-2">
                                <span class="w-3 h-3 rounded-full bg-emerald-500 animate-pulse"></span>
                                Embedding Data
                            </h2>
                            <p class="text-xs text-slate-400 mt-1 font-mono">Model: all-MiniLM-L6-v2 | Dimensions: 384
                                (Float32) | Distance Metric: Cosine Similarity</p>
                        </div>
                        <button onclick="closeVectorModal()" class="text-slate-400 hover:text-white">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>

                    <div
                        class="bg-black p-4 rounded-lg h-96 overflow-y-auto font-mono text-xs text-green-500 leading-relaxed custom-scrollbar shadow-inner">
                        <div id="vectorModalText" class="break-all whitespace-pre-wrap"></div>
                    </div>

                    <div class="mt-4 text-right">
                        <p class="text-[10px] text-slate-500 font-mono italic">
                            *Data ini adalah representasi matematis dari pesan pengguna yang dicocokkan dengan dokumen PDF
                            di ChromaDB.
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script>
            window.openModal = function(text) {
                try {
                    let parsedText = JSON.parse(text);

                    parsedText = parsedText
                        .replace(/\\n/g, '\n')
                        .replace(/\\u[\dA-F]{4}/gi, '')
                        .replace(/\*\*\*/g, '')
                        .replace(/```/g, '');

                    document.getElementById('modalText').innerHTML = marked.parse(parsedText);

                    document.getElementById('modal').classList.remove('hidden');
                } catch (e) {
                    console.error("ERROR MODAL:", e);

                    document.getElementById('modalText').innerText = text;
                    document.getElementById('modal').classList.remove('hidden');
                }
            }

            window.closeModal = function() {
                document.getElementById('modal').classList.add('hidden');
            }
        </script>


        <script>
            document.addEventListener('DOMContentLoaded', function() {

                const labels = {!! json_encode($dailyStats->pluck('date')) !!};
                const totalData = {!! json_encode($dailyStats->pluck('total')) !!};
                const successData = {!! json_encode($dailyStats->pluck('success')) !!};
                const gapData = {!! json_encode($dailyStats->pluck('gap')) !!};

                const rateData = successData.map((val, i) => {
                    const total = val + gapData[i];
                    return total > 0 ? Math.round((val / total) * 100) : 0;
                });

                new Chart(document.getElementById('trendChart'), {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                                label: 'Total',
                                data: totalData,
                                borderColor: '#ef4444',
                                tension: 0.4
                            },
                            {
                                label: 'Success',
                                data: successData,
                                borderColor: '#3b82f6',
                                tension: 0.4
                            }
                        ]
                    }
                });

                const data = [{{ $validContext }}, {{ $knowledgeGap }}, {{ $outOfContext }}];

                const relevantTotal = data[0] + data[1];
                const successPercent = relevantTotal > 0 ?
                    Math.round((data[0] / relevantTotal) * 100) :
                    0;

                new Chart(document.getElementById('chart'), {
                    type: 'doughnut',
                    data: {
                        labels: ['Jawaban Benar', 'Tidak Ditemukan', 'Jawaban Kurang Tepat'],
                        datasets: [{
                            data: data,
                            backgroundColor: ['#22c55e', '#ef4444', '#f59e0b'],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        cutout: '72%',
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    },
                    plugins: [{
                        id: 'centerText',
                        beforeDraw(chart) {
                            const {
                                ctx,
                                chartArea
                            } = chart;
                            if (!chartArea) return;

                            const centerX = (chartArea.left + chartArea.right) / 2;
                            const centerY = (chartArea.top + chartArea.bottom) / 2;

                            ctx.save();

                            ctx.font = "bold 28px sans-serif";
                            ctx.fillStyle = "#111827";
                            ctx.textAlign = "center";
                            ctx.textBaseline = "middle";
                            ctx.fillText(successPercent + "%", centerX, centerY - 8);

                            ctx.font = "12px sans-serif";
                            ctx.fillStyle = "#6b7280";
                            ctx.fillText("Jawaban Benar", centerX, centerY + 12);

                            ctx.restore();
                        }
                    }]
                });

            });
        </script>
        <script>
            window.openVectorModal = function(chatId) {
                let rawData = document.getElementById('vector-data-' + chatId).innerText;

                try {
                    let vector = JSON.parse(rawData);

                    let avg = vector.reduce((a, b) => a + b, 0) / vector.length;
                    let min = Math.min(...vector);
                    let max = Math.max(...vector);

                    let content = `
<div class="text-sm text-gray-200 space-y-2">

    <div class="text-center font-semibold text-base">
        📊 Analisis Pertanyaan
    </div>

    <div class="bg-gray-800 px-3 py-2 rounded flex justify-between">
        <span>Jumlah Data</span>
        <b>${vector.length}</b>
    </div>

    <div class="bg-gray-800 px-3 py-2 rounded flex justify-between">
        <span>Rata-rata</span>
        <b>${avg.toFixed(3)}</b>
    </div>

    <div class="bg-gray-800 px-3 py-2 rounded flex justify-between">
        <span>Nilai Terendah</span>
        <span class="text-red-400">${min.toFixed(3)}</span>
    </div>

    <div class="bg-gray-800 px-3 py-2 rounded flex justify-between">
        <span>Nilai Tertinggi</span>
        <span class="text-green-400">${max.toFixed(3)}</span>
    </div>

    <div class="text-xs text-gray-400 text-center mt-2">
        Digunakan untuk memahami pertanyaan dan mencari jawaban paling sesuai.
    </div>

</div>
        `;

                    document.getElementById('vectorModalText').innerHTML = content;
                    document.getElementById('vectorModal').classList.remove('hidden');

                } catch (e) {
                    document.getElementById('vectorModalText').innerText = "Gagal memuat data.";
                    document.getElementById('vectorModal').classList.remove('hidden');
                }
            }
        </script>
        <script>
            function labelScore(score) {
                if (score >= 0.75) return {
                    text: "Sangat Cocok",
                    color: "text-green-400"
                };
                if (score >= 0.55) return {
                    text: "Cukup Cocok",
                    color: "text-yellow-400"
                };
                return {
                    text: "Kurang Cocok",
                    color: "text-red-400"
                };
            }

            function openDocScore(id) {
                let raw = document.getElementById('doc-score-' + id).innerText;
                let docs = JSON.parse(raw);

                let html = `
<div class="text-sm text-gray-200 space-y-2">
    <div class="text-center font-semibold text-base">
        📊 Tingkat Kecocokan Dokumen
    </div>
`;

                docs.forEach((d, i) => {
                    let label = labelScore(d.score);

                    html += `
        <div class="bg-gray-800 px-3 py-2 rounded">
            <div class="flex justify-between">
                <b>Dokumen ${i + 1}</b>
                <span class="${label.color}">${label.text}</span>
            </div>

            <div class="w-full bg-gray-700 h-2 rounded mt-2">
                <div class="h-2 rounded bg-blue-400" style="width:${d.score * 100}%"></div>
            </div>

            <div class="text-xs text-gray-400 mt-1">
                Skor: ${d.score.toFixed(2)}
            </div>
        </div>
        `;
                });

                html += `</div>`;

                document.getElementById('vectorModalText').innerHTML = html;
                document.getElementById('vectorModal').classList.remove('hidden');
            }
        </script>
        <script>
            window.closeVectorModal = function() {
                document.getElementById('vectorModal').classList.add('hidden');
            }
        </script>
    @endsection
