<?php

namespace App\Filament\Resources\Hunts;

use App\Enums\HuntDifficulty;
use App\Enums\HuntStatus;
use App\Enums\UserRole;
use App\Filament\Resources\Hunts\Pages\CreateHunts;
use App\Filament\Resources\Hunts\Pages\EditHunts;
use App\Filament\Resources\Hunts\Pages\ListHunts;
use App\Models\Hunts;
use BackedEnum;
use Dotswan\MapPicker\Fields\Map;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
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\Database\Eloquent\Builder;

class HuntsResource extends Resource
{
    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        if (auth()->check() && auth()->user()->role === UserRole::ORGA) {
            $query->where('creator_id', auth()->id());
        }

        return $query;
    }

    protected static ?string $model = Hunts::class;

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

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('title')
                    ->required()
                    ->maxLength(255),
                Textarea::make('description')
                    ->columnSpanFull(),
                Select::make('status')
                    ->options(HuntStatus::class)
                    ->required(),
                Select::make('difficulty')
                    ->options(HuntDifficulty::class)
                    ->required(),
                TextInput::make('slug')
                    ->required(),
                Forms\Components\FileUpload::make('image')
                    ->image()
                    ->disk('public')
                    ->directory('hunts'),
                TextInput::make('city')
                    ->required()
                    ->maxLength(255),
                TextInput::make('start_radius_m')
                    ->numeric()
                    ->label('Start radius (meters)')
                    ->default(50),
                Forms\Components\Hidden::make('latitude'),
                Forms\Components\Hidden::make('longitude'),
                DateTimePicker::make('start_at'),
                DateTimePicker::make('end_at'),

                // Map
                Map::make('location')
                    ->label('Location')
                    ->columnSpanFull()
                // Basic Configuration
                    ->defaultLocation(latitude: 40.4168, longitude: -3.7038)
                    ->draggable(true)
                    ->clickable(true) // click to move marker
                    ->zoom(15)
                    ->minZoom(0)
                    ->maxZoom(28)
                    ->tilesUrl('https://tile.openstreetmap.org/{z}/{x}/{y}.png')
                    ->detectRetina(true)
                    ->showFullscreenControl(true)
                    ->showZoomControl(true)

                // Location Features
                    ->showMyLocationButton(true)
                    ->rangeSelectField('start_radius_m')

                // Extra Customization
                    ->extraStyles([
                        'border-radius: 10px',
                    ])
                // State Management
                    ->afterStateUpdated(function ($set, ?array $state): void {
                        $set('latitude', $state['lat']);
                        $set('longitude', $state['lng']);
                    })
                    ->afterStateHydrated(function ($state, $record, $set): void {
                        if ($record && $record->latitude && $record->longitude) {
                            $set('location', [
                                'lat' => $record->latitude,
                                'lng' => $record->longitude,
                            ]);
                        }
                    }),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('image')
                    ->disk('public'),
                Tables\Columns\TextColumn::make('title')
                    ->searchable(),
                Tables\Columns\TextColumn::make('status')
                    ->searchable(),
                Tables\Columns\TextColumn::make('difficulty'),
                Tables\Columns\TextColumn::make('city')
                    ->searchable(),
                Tables\Columns\TextColumn::make('start_at')
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                EditAction::make(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\StepsRelationManager::class,
            RelationManagers\ParticipantsRelationManager::class,
        ];
    }

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