<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TeacherResource\Pages;
use App\Models\Teacher;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class TeacherResource extends Resource
{
    protected static ?string $model = Teacher::class;

    protected static bool $shouldRegisterNavigation = false;

    public static function form(Schema $schema): Schema
    {
        return $schema->schema([
            // 基本信息字段
            TextInput::make('teacher_id')
                ->label('教师ID')
                ->disabled()
                ->columnSpanFull(),

            TextInput::make('name')
                ->label('教师姓名')
                ->required()
                ->maxLength(128)
                ->placeholder('请输入教师姓名')
                ->columnSpanFull()
                ->extraAttributes(['style' => 'height: 3rem']),

            TextInput::make('subject')
                ->label('教授科目')
                ->required()
                ->maxLength(64)
                ->placeholder('例如：数学、语文、英语等')
                ->columnSpanFull()
                ->extraAttributes(['style' => 'height: 3rem']),

            // 登录信息字段
            TextInput::make('user.username')
                ->label('手机号（登录用户名）')
                ->disabled()
                ->columnSpanFull()
                ->extraAttributes(['style' => 'height: 3rem']),

            TextInput::make('user.password_hash')
                ->label('密码')
                ->password()
                ->revealable()
                ->dehydrateStateUsing(function ($state) {
                    return $state ? Hash::make($state) : null;
                })
                ->placeholder('留空则不修改密码')
                ->helperText('留空则不修改原密码')
                ->columnSpanFull()
                ->extraAttributes(['style' => 'height: 3rem']),

            // 备注字段
            Textarea::make('remark')
                ->label('备注')
                ->rows(4)
                ->placeholder('请输入备注信息（可选）')
                ->columnSpanFull(),
        ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('teacher_id')
                    ->label('教师ID')
                    ->badge()
                    ->color('primary')
                    ->copyable()
                    ->copyMessage('教师ID已复制')
                    ->copyMessageDuration(1500)
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('姓名')
                    ->weight('bold')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('subject')
                    ->label('教授科目')
                    ->badge()
                    ->color('info')
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.username')
                    ->label('手机号（登录名）')
                    ->badge()
                    ->color('primary')
                    ->copyable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.phone')
                    ->label('备用手机号')
                    ->copyable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.email')
                    ->label('邮箱')
                    ->copyable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('students_count')
                    ->label('学生数量')
                    ->counts('students')
                    ->sortable()
                    ->alignCenter()
                    ->badge()
                    ->color('success'),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('创建时间')
                    ->dateTime('Y-m-d H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('subject')
                    ->label('教授科目')
                    ->options(fn () => self::subjectOptions())
                    ->placeholder('全部科目'),
            ])
            ->actions([
                Action::make('view')
                    ->label('查看')
                    ->icon('heroicon-o-eye')
                    ->url(fn ($record) => static::getUrl('view', ['record' => $record])),
                EditAction::make()
                    ->label('编辑')
                    ->url(fn ($record) => static::getUrl('edit', ['record' => $record])),
                Action::make('delete')
                    ->label('删除')
                    ->icon('heroicon-o-trash')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->modalDescription('确定要删除这位教师吗？此操作不可恢复。')
                    ->action(function ($record) {
                        $record->delete();
                        \Filament\Notifications\Notification::make()
                            ->success()
                            ->title('删除成功')
                            ->body("教师 {$record->name} 已被删除")
                            ->send();
                    }),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    BulkAction::make('deleteBulk')
                        ->label('批量删除')
                        ->icon('heroicon-o-trash')
                        ->color('danger')
                        ->requiresConfirmation()
                        ->modalDescription('确定要删除选中的教师吗？此操作不可恢复。')
                        ->action(function ($records) {
                            $count = $records->count();
                            foreach ($records as $record) {
                                $record->delete();
                            }
                            \Filament\Notifications\Notification::make()
                                ->success()
                                ->title('批量删除成功')
                                ->body("已删除 {$count} 位教师")
                                ->send();
                        }),
                ]),
            ])
            ->emptyStateHeading('暂无教师记录')
            ->emptyStateDescription('开始添加第一位教师吧')
            ->emptyStateActions([]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTeachers::route('/'),
            'create' => Pages\CreateTeacher::route('/create'),
            'view' => Pages\ViewTeacher::route('/{record}'),
            'edit' => Pages\EditTeacher::route('/{record}/edit'),
        ];
    }

    public static function subjectOptions(): array
    {
        return [
            'math' => '数学',
            'chinese' => '语文',
            'english' => '英语',
            'physics' => '物理',
            'chemistry' => '化学',
            'biology' => '生物',
            'history' => '历史',
            'geography' => '地理',
            'politics' => '政治',
            'other' => '其他',
        ];
    }
}
