<?php

namespace App\Filament\Resources;

use App\Filament\Resources\OnlineResourcesResource\Pages;
use App\Models\OnlineResources;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Gate;

class OnlineResourcesResource extends Resource
{
    protected static ?string $model = OnlineResources::class;

    protected static ?string $navigationIcon = 'heroicon-o-archive-box-arrow-down';
    protected static ?string $navigationLabel = 'Online Resources';
    protected static ?string $pluralLabel = 'Online Resources';
    protected static ?string $modelLabel = 'Online Resource';
    protected static ?string $navigationGroup = 'Content Management';
    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Program Information')
                    ->schema([
                        Forms\Components\Select::make('program_id')
                            ->label('Program')
                            ->relationship('program', 'main_title')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->placeholder('Select a program')
                            ->live(),
                        Forms\Components\Select::make('semester_id')
                            ->label('Semester')
                            ->options(function (callable $get) {
                                $programId = $get('program_id');
                                if (!$programId) {
                                    return [];
                                }
                                return \App\Models\Semester::where('program_id', $programId)->pluck('name', 'id');
                            })
                            ->searchable()
                            ->placeholder('Select a semester (optional)')
                            ->disabled(fn (callable $get) => !$get('program_id'))
                            ->live(),
                        Forms\Components\Select::make('subject_id')
                            ->label('Subject')
                            ->options(function (callable $get) {
                                $semesterId = $get('semester_id');
                                if (!$semesterId) {
                                    return [];
                                }
                                return \App\Models\Subject::where('semester_id', $semesterId)->pluck('name', 'id');
                            })
                            ->searchable()
                            ->placeholder('Select a subject (optional)')
                            ->disabled(fn (callable $get) => !$get('semester_id')),
                    ]),

                Forms\Components\Section::make('File Information')
                    ->schema([
                        Forms\Components\TextInput::make('file_name')
                            ->label('File Name')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Enter file name'),
                        Forms\Components\Select::make('file_category')
                            ->label('File Category')
                            ->options([
                                'lecture_notes' => 'Lecture Notes',
                                'assignments' => 'Assignments',
                                'syllabus' => 'Syllabus',
                                'study_materials' => 'Study Materials',
                                'past_papers' => 'Past Papers',
                                'tutorials' => 'Tutorials',
                                'other' => 'Other',
                            ])
                            ->required()
                            ->placeholder('Select file category'),
                        Forms\Components\DatePicker::make('file_released_date')
                            ->label('File Released Date')
                            ->required()
                            ->default(now())
                            ->placeholder('Select release date'),
                        Forms\Components\TextInput::make('file_download_count')
                            ->label('File Download Count')
                            ->numeric()
                            ->default(0)
                            ->minValue(0)
                            ->placeholder('Enter download count'),
                    ]),

                Forms\Components\Section::make('File Upload')
                    ->schema([
                        Forms\Components\FileUpload::make('file')
                            ->label('File')
                            ->disk('public')
                            ->directory('online-resources')
                            ->visibility('public')
                            ->preserveFilenames()
                            ->storeFileNamesIn('original_filename')
                            ->acceptedFileTypes([
                                'application/pdf',
                                'application/msword',
                                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                                'application/vnd.ms-excel',
                                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                                'text/plain',
                                'image/jpeg',
                                'image/png',
                                'image/gif',
                            ])
                            ->maxSize(10240) // 10MB
                            ->placeholder('Upload file (PDF, DOC, DOCX, XLS, XLSX, TXT, Images)')
                            ->columnSpanFull()
                            ->reactive()
                            ->disabled(fn (callable $get) => filled($get('file_link'))),
                        Forms\Components\TextInput::make('file_link')
                            ->label('File Link (URL)')
                            ->url()
                            ->placeholder('Paste a link to an online resource (optional)')
                            ->columnSpanFull()
                            ->reactive()
                            ->disabled(fn (callable $get) => filled($get('file'))),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('program.main_title')
                    ->label('Program')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('semester.name')
                    ->label('Semester')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('subject.name')
                    ->label('Subject')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('file_name')
                    ->label('File Name')
                    ->sortable()
                    ->searchable()
                    ->limit(30),
                Tables\Columns\TextColumn::make('file_category')
                    ->label('Category')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'lecture_notes' => 'primary',
                        'assignments' => 'success',
                        'syllabus' => 'warning',
                        'study_materials' => 'info',
                        'past_papers' => 'danger',
                        'tutorials' => 'secondary',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('file_download_count')
                    ->label('Downloads')
                    ->sortable()
                    ->badge()
                    ->color('success'),
                Tables\Columns\TextColumn::make('file_released_date')
                    ->label('Release Date')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('file_category')
                    ->options([
                        'lecture_notes' => 'Lecture Notes',
                        'assignments' => 'Assignments',
                        'syllabus' => 'Syllabus',
                        'study_materials' => 'Study Materials',
                        'past_papers' => 'Past Papers',
                        'tutorials' => 'Tutorials',
                        'other' => 'Other',
                    ]),
                Tables\Filters\Filter::make('released_this_month')
                    ->query(fn ($query) => $query->whereMonth('file_released_date', now()->month))
                    ->label('Released This Month'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make()->visible(fn () => Gate::allows('view onlineresources')),
                Tables\Actions\EditAction::make()->visible(fn () => Gate::allows('edit onlineresources')),
                Tables\Actions\DeleteAction::make()->visible(fn () => Gate::allows('delete onlineresources')),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()->visible(fn () => Gate::allows('delete onlineresources')),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListOnlineResources::route('/'),
            'create' => Pages\CreateOnlineResource::route('/create'),
            'edit' => Pages\EditOnlineResource::route('/{record}/edit'),
        ];
    }

    public static function canViewAny(): bool
    {
        return Gate::allows('view onlineresources');
    }

    public static function canView($record): bool
    {
        return Gate::allows('view onlineresources');
    }

    public static function canCreate(): bool
    {
        return Gate::allows('create onlineresources');
    }

    public static function canEdit($record): bool
    {
        return Gate::allows('edit onlineresources');
    }

    public static function canDelete($record): bool
    {
        return Gate::allows('delete onlineresources');
    }

    public static function canRestore($record): bool
    {
        return Gate::allows('restore onlineresources');
    }

    public static function canForceDelete($record): bool
    {
        return Gate::allows('force delete onlineresources');
    }
}
