<?php

namespace App\Filament\Resources\MenuPermissionResource\Pages;
use Illuminate\Database\Eloquent\Builder;

use App\Filament\Resources\MenuPermissionResource;
use App\Models\Teacher;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Forms;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;

class ListMenuPermissions extends ListRecords
{
    public ?string $selectedTeacherId = null;

    protected static string $resource = MenuPermissionResource::class;

    public function mount(): void
    {
        parent::mount();

        // 默认选择第一个老师
        if (!$this->selectedTeacherId) {
            $firstTeacher = Teacher::first();
            if ($firstTeacher) {
                $this->selectedTeacherId = $firstTeacher->teacher_id;
            }
        }
    }

    /**
     * 更新选中的老师
     */
    public function updatedSelectedTeacherId(): void
    {
        // 当老师选择改变时，刷新表格数据
        $this->resetPage();
    }

    public function table(Table $table): Table
    {
        return $table
            ->query(
                $this->selectedTeacherId
                    ? \App\Models\MenuPermission::where('user_id', $this->selectedTeacherId)
                    : \App\Models\MenuPermission::where('id', 0) // 返回空结果
            )
            ->columns([
                TextColumn::make('user_id')
                    ->label('老师ID')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('menu_key')
                    ->label('菜单标识')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('menu_label')
                    ->label('菜单名称')
                    ->searchable(),
                TextColumn::make('menu_group')
                    ->label('菜单分组')
                    ->badge()
                    ->color('gray'),
                TextColumn::make('menu_url')
                    ->label('菜单URL')
                    ->limit(50)
                    ->copyable(),
                ToggleColumn::make('is_visible')
                    ->label('是否可见')
                    ->sortable(),
                TextColumn::make('sort_order')
                    ->label('排序')
                    ->sortable(),
                TextColumn::make('created_at')
                    ->label('创建时间')
                    ->dateTime('Y-m-d H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('menu_group')
                    ->label('菜单分组')
                    ->options([
                        '管理' => '管理',
                        '工具' => '工具',
                        '分析' => '分析',
                    ])
                    ->multiple(),
                TernaryFilter::make('is_visible')
                    ->label('可见状态')
                    ->placeholder('全部')
                    ->trueLabel('可见')
                    ->falseLabel('隐藏'),
            ])
            ->actions([
                Actions\EditAction::make(),
                Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Actions\BulkActionGroup::make([
                    Actions\DeleteBulkAction::make(),
                    Actions\BulkAction::make('toggle_visibility')
                        ->label('批量切换可见性')
                        ->icon('heroicon-m-eye')
                        ->action(function ($records) {
                            foreach ($records as $record) {
                                $record->update(['is_visible' => !$record->is_visible]);
                            }
                        }),
                ]),
            ])
            ->defaultSort('sort_order')
            ->paginated([10, 25, 50, 100])
            ->poll('30s');
    }

    protected function getHeaderActions(): array
    {
        $teacher = $this->selectedTeacherId
            ? Teacher::where('teacher_id', $this->selectedTeacherId)->first()
            : null;

        return [
            Actions\CreateAction::make()
                ->visible(fn () => $this->selectedTeacherId !== null),

            Actions\Action::make('初始化选中老师菜单')
                ->label('为当前老师初始化菜单')
                ->icon('heroicon-o-plus-circle')
                ->color('success')
                ->visible(fn () => $this->selectedTeacherId !== null)
                ->action(function () use ($teacher) {
                    if (!$teacher) {
                        \Filament\Notifications\Notification::make()
                            ->title('错误')
                            ->body('请先选择老师')
                            ->danger()
                            ->send();
                        return;
                    }

                    $menuKeys = [
                        'dashboard' => ['label' => '仪表盘', 'group' => '管理', 'sort' => 0],
                        'exam-history' => ['label' => '考试历史', 'group' => '管理', 'sort' => 1],
                        'exam-analysis' => ['label' => '考试分析', 'group' => '分析', 'sort' => 2],
                        'ocr-paper-grading' => ['label' => 'OCR试卷批改', 'group' => '工具', 'sort' => 3],
                        'intelligent-exam-generation' => ['label' => '智能出卷', 'group' => '工具', 'sort' => 4],
                        'knowledge-graph' => ['label' => '知识图谱', 'group' => '分析', 'sort' => 5],
                        'student-management' => ['label' => '学生管理', 'group' => '管理', 'sort' => 6],
                        'teacher-management' => ['label' => '老师管理', 'group' => '管理', 'sort' => 7],
                    ];

                    foreach ($menuKeys as $key => $data) {
                        \App\Models\MenuPermission::updateOrCreate(
                            [
                                'user_id' => $teacher->teacher_id,
                                'menu_key' => $key,
                            ],
                            [
                                'menu_label' => $data['label'],
                                'menu_group' => $data['group'],
                                'is_visible' => true,
                                'sort_order' => $data['sort'],
                            ]
                        );
                    }

                    // 刷新表格数据
                    $this->resetPage();

                    \Filament\Notifications\Notification::make()
                        ->title('菜单初始化完成')
                        ->body('已为老师 ' . $teacher->teacher_id . ' 初始化菜单权限')
                        ->success()
                        ->send();
                }),

            Actions\Action::make('初始化所有老师菜单')
                ->label('为所有老师初始化菜单')
                ->icon('heroicon-o-users')
                ->color('primary')
                ->action(function () {
                    $teachers = Teacher::all();

                    $menuKeys = [
                        'dashboard' => ['label' => '仪表盘', 'group' => '管理', 'sort' => 0],
                        'exam-history' => ['label' => '考试历史', 'group' => '管理', 'sort' => 1],
                        'exam-analysis' => ['label' => '考试分析', 'group' => '分析', 'sort' => 2],
                        'ocr-paper-grading' => ['label' => 'OCR试卷批改', 'group' => '工具', 'sort' => 3],
                        'intelligent-exam-generation' => ['label' => '智能出卷', 'group' => '工具', 'sort' => 4],
                        'knowledge-graph' => ['label' => '知识图谱', 'group' => '分析', 'sort' => 5],
                        'student-management' => ['label' => '学生管理', 'group' => '管理', 'sort' => 6],
                        'teacher-management' => ['label' => '老师管理', 'group' => '管理', 'sort' => 7],
                    ];

                    foreach ($teachers as $teacher) {
                        foreach ($menuKeys as $key => $data) {
                            \App\Models\MenuPermission::updateOrCreate(
                                [
                                    'user_id' => $teacher->teacher_id,
                                    'menu_key' => $key,
                                ],
                                [
                                    'menu_label' => $data['label'],
                                    'menu_group' => $data['group'],
                                    'is_visible' => true,
                                    'sort_order' => $data['sort'],
                                ]
                            );
                        }
                    }

                    \Filament\Notifications\Notification::make()
                        ->title('菜单初始化完成')
                        ->body('已为 ' . $teachers->count() . ' 位老师初始化菜单权限')
                        ->success()
                        ->send();
                }),
        ];
    }

    protected function getTableContentGrid(): ?array
    {
        return [
            'md' => 2,
            'xl' => 3,
        ];
    }

    protected function getTableHeader(): \Illuminate\Contracts\View\View|\Illuminate\Contracts\Support\Htmlable|null
    {
        $teacher = $this->selectedTeacherId
            ? Teacher::where('teacher_id', $this->selectedTeacherId)->first()
            : null;

        if ($teacher) {
            return view('filament.resources.menu-permission-resource.header', [
                'teacher' => $teacher,
            ]);
        }

        return null;
    }
}
