<x-filament-panels::page>

<!-- 数学公式渲染组件 -->
<x-math-render />

<div class="space-y-6">
    @php
        $questionsData = $this->questions;
        $metaData = $this->meta;
        $statisticsData = $this->statistics;
    @endphp

    <div class="flex justify-end">
        <a
            href="{{ url('/admin/question-generation') }}"
            class="inline-flex items-center justify-center px-4 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-lg transition-colors"
        >
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
            </svg>
            生成题目
        </a>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="bg-white p-4 rounded-lg border">
            <div class="text-sm text-gray-500">题目总数</div>
            <div class="text-2xl font-bold text-primary-600">{{ $statisticsData['total'] ?? 0 }}</div>
        </div>
        <div class="bg-white p-4 rounded-lg border">
            <div class="text-sm text-gray-500">基础难度 (≤0.4)</div>
            <div class="text-2xl font-bold text-green-600">
                @php
                    $basicCount = 0;
                    foreach ($statisticsData['by_difficulty'] ?? [] as $key => $value) {
                        if ((float)$key <= 0.4) {
                            $basicCount += $value;
                        }
                    }
                    echo $basicCount;
                @endphp
            </div>
        </div>
        <div class="bg-white p-4 rounded-lg border">
            <div class="text-sm text-gray-500">中等难度 (0.4-0.7)</div>
            <div class="text-2xl font-bold text-yellow-600">
                @php
                    $mediumCount = 0;
                    foreach ($statisticsData['by_difficulty'] ?? [] as $key => $value) {
                        if ((float)$key > 0.4 && (float)$key <= 0.7) {
                            $mediumCount += $value;
                        }
                    }
                    echo $mediumCount;
                @endphp
            </div>
        </div>
        <div class="bg-white p-4 rounded-lg border">
            <div class="text-sm text-gray-500">拔高难度 (>0.7)</div>
            <div class="text-2xl font-bold text-red-600">
                @php
                    $advancedCount = 0;
                    foreach ($statisticsData['by_difficulty'] ?? [] as $key => $value) {
                        if ((float)$key > 0.7) {
                            $advancedCount += $value;
                        }
                    }
                    echo $advancedCount;
                @endphp
            </div>
        </div>
    </div>

    <div class="bg-white p-4 rounded-lg border">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">搜索题目</label>
                <input type="text" wire:model.live.debounce.300ms="search" placeholder="输入关键词" class="w-full border rounded p-2">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">知识点筛选</label>
                <input type="text" wire:model.live="selectedKpCode" placeholder="KP1001" class="w-full border rounded p-2">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">难度筛选</label>
                <input type="text" wire:model.live="selectedDifficulty" placeholder="0.3/0.6/0.85" class="w-full border rounded p-2">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">每页显示</label>
                <input type="number" wire:model.live="perPage" min="10" max="100" step="5" class="w-full border rounded p-2">
            </div>
        </div>
    </div>

    <div class="bg-white rounded-lg border overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">题目编号</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">知识点</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">创建时间</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">题干</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">难度</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">操作</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                @forelse($questionsData as $question)
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap">{{ $question['question_code'] ?? 'N/A' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ $question['kp_name'] ?? $question['kp_code'] ?? 'N/A' }}</div>
                            @if(!empty($question['kp_code']))
                                <div class="text-xs text-gray-500">{{ $question['kp_code'] }}</div>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                            @if(!empty($question['created_at']))
                                {{ \Carbon\Carbon::parse($question['created_at'])->toDateTimeString() }}
                            @else
                                -
                            @endif
                        </td>
                        <td class="px-6 py-4" style="word-wrap: break-word; white-space: normal; line-height: 1.8; max-width: 400px;">
                            <span class="text-sm">
                                @math($question['stem'] ?? 'N/A')
                            </span>
                        </td>
                        <td class="px-6 py-4">
                            @php
                                $difficulty = $question['difficulty'] ?? null;
                                $label = match (true) {
                                    !$difficulty => 'N/A',
                                    (float)$difficulty <= 0.4 => '基础',
                                    (float)$difficulty <= 0.7 => '中等',
                                    default => '拔高',
                                };
                            @endphp
                            {{ $label }}
                            @if(app()->environment('local'))
                                <span class="text-xs text-gray-400">({{ $difficulty }})</span>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button wire:click="viewQuestion('{{ $question['question_code'] }}')" class="text-blue-600 hover:underline mr-3">详情</button>
                            <button wire:click="deleteQuestion('{{ $question['question_code'] }}')" class="text-red-600 hover:underline">删除</button>
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="5" class="px-6 py-12 text-center">暂无数据</td></tr>
                @endforelse
            </tbody>
        </table>

        @if(!empty($metaData) && ($metaData['total'] ?? 0) > 0)
            <div class="px-4 py-3 border-t border-gray-200 flex items-center justify-between">
                <div class="text-sm text-gray-700">共 {{ $metaData['total'] ?? 0 }} 条记录</div>
                <div class="flex items-center gap-2">
                    <button wire:click="previousPage" @disabled($currentPage <= 1) class="px-3 py-1 border rounded">上一页</button>
                    @foreach($this->getPages() as $page)
                        <button wire:click="gotoPage({{ $page }})" class="px-3 py-1 border rounded {{ $page === $currentPage ? 'bg-blue-50 text-blue-700' : '' }}">{{ $page }}</button>
                    @endforeach
                    <button wire:click="nextPage" @disabled($currentPage >= ($metaData['total_pages'] ?? 1)) class="px-3 py-1 border rounded">下一页</button>
                </div>
            </div>
        @endif
    </div>

    {{-- 详情侧边栏 --}}
    @if($showDetailModal)
        <div class="fixed inset-0 z-40 flex">
            <div class="flex-1 bg-black/40" wire:click="$set('showDetailModal', false)"></div>
            <div class="w-full max-w-3xl bg-white shadow-xl overflow-y-auto">
                <div class="p-6 border-b flex justify-between items-center">
                    <div>
                        <h3 class="text-lg font-semibold">{{ $editing['question_code'] ?? '题目详情' }}</h3>
                        <p class="text-sm text-gray-500">
                            {{ $editing['kp_name'] ?? ($editing['kp_code'] ?? '') }}
                            @if(!empty($editing['kp_code'])) ({{ $editing['kp_code'] }}) @endif
                        </p>
                    </div>
                    <button class="text-gray-500 hover:text-gray-700" wire:click="$set('showDetailModal', false)">&times;</button>
                </div>
                <div class="p-6 space-y-4">
                    <div>
                        <label class="text-sm font-medium text-gray-700">知识点代码</label>
                        <input type="text" wire:model="editing.kp_code" class="w-full border rounded px-3 py-2 text-sm">
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">题干</label>
                        <textarea wire:model="editing.stem" rows="4" class="w-full border rounded px-3 py-2 text-sm"></textarea>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">答案</label>
                        <textarea wire:model="editing.answer" rows="3" class="w-full border rounded px-3 py-2 text-sm"></textarea>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">解析</label>
                        <textarea wire:model="editing.solution" rows="4" class="w-full border rounded px-3 py-2 text-sm"></textarea>
                    </div>
                    <div class="grid grid-cols-2 gap-4 text-sm">
                        <div>
                            <label class="text-sm font-medium text-gray-700">难度 (0-1)</label>
                            <input type="number" step="0.01" min="0" max="1" wire:model="editing.difficulty" class="w-full border rounded px-3 py-2 text-sm">
                        </div>
                        <div>
                            <label class="text-sm font-medium text-gray-700">题型</label>
                            <input type="text" wire:model="editing.question_type" class="w-full border rounded px-3 py-2 text-sm" placeholder="choice/fill/answer">
                        </div>
                        <div>
                            <label class="text-sm font-medium text-gray-700">来源</label>
                            <input type="text" wire:model="editing.source" class="w-full border rounded px-3 py-2 text-sm">
                        </div>
                        <div>
                            <label class="text-sm font-medium text-gray-700">标签</label>
                            <input type="text" wire:model="editing.tags" class="w-full border rounded px-3 py-2 text-sm">
                        </div>
                        <div class="col-span-2">
                            <label class="text-sm font-medium text-gray-700">技能（逗号分隔）</label>
                            <input type="text" wire:model="editing.skills_text" class="w-full border rounded px-3 py-2 text-sm">
                        </div>
                        <div><span class="font-medium">创建时间：</span>{{ $editing['created_at'] ?? '-' }}</div>
                        <div><span class="font-medium">更新时间：</span>{{ $editing['updated_at'] ?? '-' }}</div>
                    </div>
                </div>
                <div class="p-6 border-t flex justify-end gap-3">
                    <button class="px-4 py-2 border rounded text-sm" wire:click="$set('showDetailModal', false)">取消</button>
                    <button class="px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700" wire:click="saveQuestion">保存</button>
                </div>
            </div>
        </div>
    @endif

    </x-filament-panels::page>

<script>
document.addEventListener('livewire:init', () => {
    // 定期检查通知
    let checkCount = 0;
    const maxChecks = 30; // 最多检查30次（15秒）

    function checkForNotifications() {
        checkCount++;

        // 使用 fetch 检查是否有新的通知
        fetch('/admin/question-management/check-notifications', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.hasNotification && data.notification) {
                // 刷新页面以显示通知
                window.location.reload();
            } else if (checkCount < maxChecks) {
                // 继续检查
                setTimeout(checkForNotifications, 500);
            }
        })
        .catch(error => {
            console.error('检查通知失败:', error);
            if (checkCount < maxChecks) {
                setTimeout(checkForNotifications, 500);
            }
        });
    }

    // 页面加载后开始检查
    setTimeout(checkForNotifications, 1000);
});
</script>
