<?php

declare(strict_types=1);

namespace App\Filament\Resources\ClassCourses;

use App\Filament\Resources\ClassCourses\Pages\CreateClassCourse;
use App\Filament\Resources\ClassCourses\Pages\EditClassCourse;
use App\Filament\Resources\ClassCourses\Pages\ListClassCourses;
use App\Models\ClassCourse;
use App\Models\User;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\BaseFileUpload;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use UnitEnum;

class ClassCourseResource extends Resource
{
    protected static ?string $model = ClassCourse::class;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $slug = 'class-courses';

    protected static ?string $navigationLabel = '課程管理';

    protected static string|UnitEnum|null $navigationGroup = '課表管理';

    protected static ?int $navigationSort = 20;

    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $modelLabel = '課程';

    protected static ?string $pluralModelLabel = '課程';

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-academic-cap';

    public static function canViewAny(): bool
    {
        $user = Auth::user();

        return $user instanceof User
            && $user->hasAnyRole(['super_admin', 'admin']);
    }

    public static function canCreate(): bool
    {
        return static::canViewAny();
    }

    public static function canEdit(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function canDelete(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Grid::make()
                    ->schema([
                        Section::make()
                            ->schema([
                                TextInput::make('name')
                                    ->label('名稱')
                                    ->required()
                                    ->maxLength(150),

                                FileUpload::make('cover_image_path')
                                    ->label('封面')
                                    ->disk('public')
                                    ->directory('classes/courses')
                                    ->image()
                                    ->saveUploadedFileUsing(static fn (BaseFileUpload $component, TemporaryUploadedFile $file): ?string =>
                                        \App\Support\Uploads\ImageVariants::store($component, $file)
                                    )
                                    ->deleteUploadedFileUsing(static function (BaseFileUpload $component, string $file): void {
                                        \App\Support\Uploads\ImageVariants::delete($component, $file);
                                    })
                                    ->maxSize(4096),

                                TextInput::make('level')
                                    ->label('程度')
                                    ->maxLength(50)
                                    ->nullable(),

                                Select::make('classroom')
                                    ->label('上課教室')
                                    ->options([
                                        '有氧團體教室' => '有氧團體教室',
                                        '飛輪教室' => '飛輪教室',
                                    ])
                                    ->nullable(),

                                TextInput::make('duration_minutes')
                                    ->label('時長（分鐘）')
                                    ->numeric()
                                    ->nullable(),

                                Textarea::make('summary')
                                    ->label('摘要')
                                    ->maxLength(500)
                                    ->columnSpanFull(),

                                RichEditor::make('content')
                                    ->label('內容')
                                    ->columnSpanFull(),

                                Toggle::make('is_active')
                                    ->label('啟用')
                                    ->default(true),

                                TextInput::make('sort_order')
                                    ->label('排序')
                                    ->numeric()
                                    ->default(0)
                                    ->required(),
                            ])
                            ->columns([
                                'sm' => 2,
                                'lg' => 3,
                            ])
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                ImageColumn::make('cover_image_path')
                    ->label('封面')
                    ->disk('public')
                    ->getStateUsing(fn (ClassCourse $record): ?string =>
                        \App\Support\Uploads\ImageVariants::preferredPath($record->cover_image_path, variant: 'medium', diskName: 'public')
                    )
                    ->square(),

                TextColumn::make('name')
                    ->label('名稱')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('classroom')
                    ->label('上課教室')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('level')
                    ->label('程度')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('duration_minutes')
                    ->label('時長')
                    ->numeric()
                    ->sortable(),

                ToggleColumn::make('is_active')
                    ->label('啟用')
                    ->sortable(),

                TextColumn::make('sort_order')
                    ->label('排序')
                    ->numeric()
                    ->sortable(),

                TextColumn::make('updated_at')
                    ->label('更新')
                    ->dateTime('Y-m-d H:i')
                    ->sortable(),
            ])
            ->reorderable('sort_order')
            ->actions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->bulkActions([
                DeleteBulkAction::make(),
            ])
            ->defaultSort('sort_order', 'asc');
    }

    public static function getPages(): array
    {
        return [
            'index' => ListClassCourses::route('/'),
            'create' => CreateClassCourse::route('/create'),
            'edit' => EditClassCourse::route('/{record}/edit'),
        ];
    }
}
