<?php

namespace App\Filament\Resources\Hunts\RelationManagers;

use Dotswan\MapPicker\Fields\Map;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;

class StepsRelationManager extends RelationManager
{
    protected static string $relationship = 'steps';

    public function form(Schema $schema): Schema
    {
        $ownerRecord = $this->getOwnerRecord();
        $defaultLocation = ($ownerRecord->latitude !== null && $ownerRecord->longitude !== null)
            ? [
                'lat' => (float) $ownerRecord->latitude,
                'lng' => (float) $ownerRecord->longitude,
            ]
            : null;

        return $schema
            ->components([
                TextInput::make('step_number')
                    ->required()
                    ->numeric(),
                TextInput::make('title')
                    ->required()
                    ->maxLength(255),
                Textarea::make('description'),
                Textarea::make('hint_text')
                    ->label('Hint'),
                FileUpload::make('hint_media_url')
                    ->label('Hint image')
                    ->image()
                    ->disk('public')
                    ->directory('hunt-steps'),
                Hidden::make('latitude')
                    ->default($defaultLocation['lat'] ?? null)
                    ->required(),
                Hidden::make('longitude')
                    ->default($defaultLocation['lng'] ?? null)
                    ->required(),
                TextInput::make('radius_m')
                    ->numeric()
                    ->label('Radius (meters)')
                    ->default(20),
                TextInput::make('xp')
                    ->numeric()
                    ->default(10),
                Map::make('location')
                    ->label('Location')
                    ->columnSpanFull()
                    ->default($defaultLocation)
                    ->defaultLocation(
                        latitude: $defaultLocation['lat'] ?? 40.4168,
                        longitude: $defaultLocation['lng'] ?? -3.7038,
                    )
                    ->draggable(true)
                    ->clickable(true)
                    ->zoom(15)
                    ->minZoom(0)
                    ->maxZoom(28)
                    ->tilesUrl('https://tile.openstreetmap.org/{z}/{x}/{y}.png')
                    ->detectRetina(true)
                    ->showFullscreenControl(false)
                    ->showZoomControl(true)
                    ->showMyLocationButton(true)
                    ->boundaries(true, 49.5, -11, 61, 2)
                    ->rangeSelectField('radius_m')
                    ->extraStyles([
                        'border-radius: 10px',
                    ])
                    ->afterStateUpdated(function ($set, ?array $state): void {
                        if ($state === null) {
                            return;
                        }

                        $set('latitude', $state['lat']);
                        $set('longitude', $state['lng']);
                    })
                    ->afterStateHydrated(function (?array $state, $record, $set) use ($defaultLocation): void {
                        if (($state['lat'] ?? null) !== null && ($state['lng'] ?? null) !== null) {
                            return;
                        }

                        $latitude = $record?->latitude ?? ($defaultLocation['lat'] ?? null);
                        $longitude = $record?->longitude ?? ($defaultLocation['lng'] ?? null);

                        if ($latitude === null || $longitude === null) {
                            return;
                        }

                        $location = [
                            'lat' => (float) $latitude,
                            'lng' => (float) $longitude,
                        ];

                        $set('location', $location);
                        $set('latitude', $location['lat']);
                        $set('longitude', $location['lng']);
                    }),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('title')
            ->columns([
                Tables\Columns\TextColumn::make('step_number')->sortable(),
                Tables\Columns\ImageColumn::make('hint_media_url')
                    ->label('Hint image')
                    ->disk('public'),
                Tables\Columns\TextColumn::make('title'),
                Tables\Columns\TextColumn::make('latitude'),
                Tables\Columns\TextColumn::make('longitude'),
                Tables\Columns\TextColumn::make('xp'),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                CreateAction::make(),
            ])
            ->actions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }
}
