<div>

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

    {{-- 后台生成状态栏 - 仅在生成中显示 --}}
    @if($isGenerating && $currentTaskId)
        <div class="alert alert-info shadow-lg animate-pulse">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current shrink-0 w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
            <div>
                <h3 class="font-bold">正在后台生成题目...</h3>
                <div class="text-xs">任务 ID: {{ $currentTaskId }} | AI生成完成后将自动刷新页面</div>
            </div>
            <button type="button" wire:click="$set('isGenerating', false)" class="btn btn-sm btn-ghost">关闭</button>
        </div>
    @endif

    <div class="flex justify-end">
        <button
            type="button"
            wire:click="$dispatch('ai-generate')"
            class="btn btn-primary"
        >
            <svg class="w-5 h-5 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>
            生成题目
        </button>
    </div>

    {{-- 难度统计卡片 --}}
    @php
        // 显示统计数据的标签
        $statsLabel = $this->selectedKpCode ? "知识点 {$this->selectedKpCode}" : "全部题目";
        $displayStats = $statisticsData;
    @endphp

    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="stats shadow bg-base-100 border">
            <div class="stat">
                <div class="stat-title">题目总数</div>
                <div class="stat-value text-primary">{{ $displayStats['total'] ?? 0 }}</div>
                <div class="stat-desc">当前题库总量</div>
            </div>
        </div>

        <div class="stats shadow bg-base-100 border">
            <div class="stat">
                <div class="stat-title">简单题 (≤0.4)</div>
                <div class="stat-value text-success">
                    @php
                        $basicCount = 0;
                        foreach ($displayStats['by_difficulty'] ?? [] as $key => $value) {
                            if ((float)$key <= 0.4) {
                                $basicCount += $value;
                            }
                        }
                        echo $basicCount;
                    @endphp
                </div>
            </div>
        </div>

        <div class="stats shadow bg-base-100 border">
            <div class="stat">
                <div class="stat-title">中等题 (0.4-0.7)</div>
                <div class="stat-value text-warning">
                    @php
                        $mediumCount = 0;
                        foreach ($displayStats['by_difficulty'] ?? [] as $key => $value) {
                            if ((float)$key > 0.4 && (float)$key <= 0.7) {
                                $mediumCount += $value;
                            }
                        }
                        echo $mediumCount;
                    @endphp
                </div>
            </div>
        </div>

        <div class="stats shadow bg-base-100 border">
            <div class="stat">
                <div class="stat-title">拔高题 (>0.7)</div>
                <div class="stat-value text-error">
                    @php
                        $advancedCount = 0;
                        foreach ($displayStats['by_difficulty'] ?? [] as $key => $value) {
                            if ((float)$key > 0.7) {
                                $advancedCount += $value;
                            }
                        }
                        echo $advancedCount;
                    @endphp
                </div>
            </div>
        </div>
    </div>

    {{-- 筛选区域 --}}
    <div class="card bg-base-100 shadow-sm border">
        <div class="card-body p-4">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
                <div class="form-control">
                    <label class="label"><span class="label-text">搜索题目</span></label>
                    <input type="text" wire:model.live.debounce.300ms="search" placeholder="输入关键词" class="input input-bordered w-full input-sm">
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">知识点筛选</span></label>
                    <input type="text" wire:model.live="selectedKpCode" placeholder="KP1001" class="input input-bordered w-full input-sm">
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">难度筛选</span></label>
                    <select wire:model.live="selectedDifficulty" class="select select-bordered w-full select-sm">
                        <option value="">全部难度</option>
                        <option value="0.3">简单 (0.3)</option>
                        <option value="0.6">中等 (0.6)</option>
                        <option value="0.85">拔高 (0.85)</option>
                    </select>
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">题目类型</span></label>
                    <select wire:model.live="selectedType" class="select select-bordered w-full select-sm">
                        <option value="">全部类型</option>
                        @foreach($this->questionTypeOptions as $value => $label)
                            <option value="{{ $value }}">{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">每页显示</span></label>
                    <select wire:model.live="perPage" class="select select-bordered w-full select-sm">
                        <option value="10">10 条</option>
                        <option value="25">25 条</option>
                        <option value="50">50 条</option>
                        <option value="100">100 条</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    {{-- 题目列表 --}}
    <div class="overflow-x-auto bg-base-100 rounded-lg shadow border">
        <table class="table table-zebra w-full">
            <thead>
                <tr>
                    <th>题目编号</th>
                    <th>知识点</th>
                    <th>类型</th>
                    <th>题干</th>
                    <th>难度</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                @forelse($questionsData as $question)
                    <tr class="hover">
                        <td class="font-mono text-xs">{{ $question['question_code'] ?? 'N/A' }}</td>
                        <td>
                            <div class="badge badge-ghost">{{ $question['kp_code'] ?? 'N/A' }}</div>
                        </td>
                        <td>
                            @php
                                $type = $question['type'] ?? 'CHOICE';
                                $typeLabel = $this->questionTypeOptions[$type] ?? $type;
                                $typeClass = match($type) {
                                    'CHOICE', 'MULTIPLE_CHOICE' => 'badge-info',
                                    'FILL_IN_THE_BLANK' => 'badge-warning',
                                    'CALCULATION', 'WORD_PROBLEM', 'PROOF' => 'badge-error',
                                    default => 'badge-ghost'
                                };
                            @endphp
                            <div class="badge {{ $typeClass }} badge-outline text-xs">{{ $typeLabel }}</div>
                        </td>
                        <td class="max-w-md">
                            <div class="prose prose-sm max-w-none">
                                <x-math-render :content="\Illuminate\Support\Str::limit($question['stem'] ?? 'N/A', 150)" class="text-sm" />
                            </div>
                        </td>
                        <td>
                            @php
                                $difficulty = $question['difficulty'] ?? null;
                                $label = match (true) {
                                    !$difficulty => 'N/A',
                                    (float)$difficulty <= 0.4 => '基础',
                                    (float)$difficulty <= 0.7 => '中等',
                                    default => '拔高',
                                };
                                $colorClass = match (true) {
                                    !$difficulty => 'badge-ghost',
                                    (float)$difficulty <= 0.4 => 'badge-success',
                                    (float)$difficulty <= 0.7 => 'badge-warning',
                                    default => 'badge-error',
                                };
                            @endphp
                            <div class="badge {{ $colorClass }} gap-1">
                                {{ $label }}
                                @if(app()->environment('local'))
                                    <span class="text-[10px] opacity-70">({{ $difficulty }})</span>
                                @endif
                            </div>
                        </td>
                        <td class="space-x-2">
                            <a href="{{ url('/admin/question-detail/' . urlencode($question['id'] ?? $question['question_code'] ?? '')) }}" class="btn btn-ghost btn-xs text-primary">
                                查看
                            </a>
                            <button 
                                wire:click="deleteQuestion('{{ $question['question_code'] }}')" 
                                wire:confirm="确定要删除这道题目吗？此操作不可恢复。"
                                class="btn btn-outline btn-xs text-error border-error"
                            >
                                删除
                            </button>
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="6" class="text-center py-10 text-gray-500">暂无数据</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>

    {{-- 分页 --}}
    @if(!empty($metaData) && ($metaData['total'] ?? 0) > 0)
        <div class="flex justify-between items-center bg-base-100 p-4 rounded-lg border shadow-sm">
            <div class="text-sm text-gray-500">共 {{ $metaData['total'] ?? 0 }} 条记录</div>
            <div class="join">
                <button class="join-item btn btn-sm" wire:click="previousPage" @disabled($currentPage <= 1)>«</button>
                
                @foreach($this->getPages() as $page)
                    <button 
                        class="join-item btn btn-sm {{ $page === $currentPage ? 'btn-active btn-primary' : '' }}" 
                        wire:click="gotoPage({{ $page }})"
                    >
                        {{ $page }}
                    </button>
                @endforeach
                
                <button class="join-item btn btn-sm" wire:click="nextPage" @disabled($currentPage >= ($metaData['total_pages'] ?? 1))>»</button>
            </div>
        </div>
    @endif

    {{-- 生成模态框 --}}
    @if($showGenerateModal)
        <div class="modal modal-open">
            <div class="modal-box w-11/12 max-w-2xl">
                <h3 class="font-bold text-lg mb-6">智能题目生成</h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="form-control w-full">
                        <label class="label"><span class="label-text font-semibold">知识点 <span class="text-error">*</span></span></label>
                        <select wire:model.live="generateKpCode" class="select select-bordered w-full">
                            <option value="">请选择知识点</option>
                            @foreach($this->knowledgePointOptions as $code => $name)
                                <option value="{{ $code }}">{{ $code }} - {{ $name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="form-control w-full">
                        <label class="label"><span class="label-text font-semibold">题目数量</span></label>
                        <input type="number" wire:model="questionCount" min="1" max="500" class="input input-bordered w-full">
                    </div>

                    <div class="form-control w-full">
                        <label class="label"><span class="label-text font-semibold">难度偏好</span></label>
                        <select wire:model="generateDifficulty" class="select select-bordered w-full">
                            <option value="">随机难度</option>
                            <option value="0.3">简单 (0.3)</option>
                            <option value="0.6">中等 (0.6)</option>
                            <option value="0.85">拔高 (0.85)</option>
                        </select>
                    </div>

                    <div class="form-control w-full">
                        <label class="label"><span class="label-text font-semibold">题目类型</span></label>
                        <select wire:model="generateType" class="select select-bordered w-full">
                            <option value="">随机类型</option>
                            @foreach($this->questionTypeOptions as $value => $label)
                                <option value="{{ $value }}">{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                @if(!empty($this->skillsOptions))
                    <div class="divider">关联技能</div>
                    <div class="form-control">
                        <div class="flex justify-between items-center mb-2">
                            <label class="label-text font-semibold">选择技能 <span class="text-error">*</span></label>
                            <button type="button" class="btn btn-xs btn-ghost text-primary" wire:click="toggleAllSkills">
                                {{ count($selectedSkills) === count($this->skillsOptions) ? '取消全选' : '全选' }}
                            </button>
                        </div>
                        <div class="grid grid-cols-2 gap-2 max-h-48 overflow-y-auto p-2 border rounded-lg bg-base-50">
                            @foreach($this->skillsOptions as $skill)
                                <label class="label cursor-pointer justify-start gap-2 hover:bg-base-200 rounded p-1">
                                    <input type="checkbox" value="{{ $skill['code'] }}" wire:model="selectedSkills" class="checkbox checkbox-primary checkbox-sm">
                                    <span class="label-text text-xs">
                                        <span class="font-bold">{{ $skill['code'] }}</span>
                                        {{ $skill['name'] }}
                                    </span>
                                </label>
                            @endforeach
                        </div>
                    </div>
                @elseif($generateKpCode)
                    <div class="alert alert-warning mt-4">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>
                        <span>该知识点下暂无关联技能，无法生成题目。</span>
                    </div>
                @endif

                <div class="modal-action">
                    <button type="button" wire:click="closeGenerateModal" class="btn" @disabled($isGenerating)>取消</button>
                    <button 
                        type="button" 
                        wire:click="executeGenerate"
                        class="btn btn-primary"
                        @disabled($isGenerating || empty($selectedSkills))
                    >
                        @if($isGenerating)
                            <span class="loading loading-spinner"></span>
                            生成中...
                        @else
                            开始生成
                        @endif
                    </button>
                </div>
            </div>
        </div>
    @endif

    <script>
        document.addEventListener('livewire:init', () => {
            Livewire.on('ai-generate', () => {
                @this.call('openGenerateModal');
            });

            Livewire.on('refresh-page', () => {
                document.dispatchEvent(new Event('math:render'));
            });

            // 监听页面刷新事件
            Livewire.on('refresh-page', () => {
                console.log('[QuestionGen] 收到刷新页面事件');
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            });

            // 任务监控逻辑
            Livewire.on('start-async-task-monitoring', () => {
                console.log('[QuestionGen] 开始监控任务状态');
                const taskId = @this.currentTaskId;

                if (!taskId) return;

                window.currentTaskId = taskId;
                let checkCount = 0;
                const maxChecks = 10; // 增加检查次数

                function checkCallbackStatus() {
                    checkCount++;
                    console.log(`[QuestionGen] 检查回调 #${checkCount}/${maxChecks}`);

                    fetch(`/api/questions/callback/${taskId}`, {
                        method: 'GET',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'Accept': 'application/json',
                        }
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status) {
                                if (data.status === 'completed') {
                                    @this.set('isGenerating', false);
                                    @this.set('currentTaskId', null);
                                    setTimeout(() => window.location.reload(), 1000);
                                } else if (data.status === 'failed') {
                                    @this.set('isGenerating', false);
                                    @this.set('currentTaskId', null);
                                }
                            } else if (checkCount < maxChecks) {
                                setTimeout(checkCallbackStatus, 3000);
                            } else {
                                @this.set('isGenerating', false);
                                @this.set('currentTaskId', null);
                            }
                        })
                        .catch(error => {
                            if (checkCount < maxChecks) {
                                setTimeout(checkCallbackStatus, 3000);
                            }
                        });
                }

                checkCallbackStatus();
            });
        });
    </script>
</div>

</div>
