<?php

namespace App\Filament\Resources;

use App\Enums\LicenseStatus;
use App\Filament\Exports\WellLicenseExporter;
use App\Filament\Resources\WellLicenseResource\Pages;
use App\Models\State;
use App\Models\WellLicense;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Cheesegrits\FilamentGoogleMaps\Fields\Map;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class WellLicenseResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = WellLicense::class;

    protected static ?string $navigationIcon = 'heroicon-o-beaker';

    protected static ?int $navigationSort = 1;

    public static function getModelLabel(): string
    {
        return __('well_license.well_license');
    }

    public static function getPluralModelLabel(): string
    {
        return __('well_license.well_licenses');
    }

    public static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.license_management');
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'restore',
            'restore_any',
            'replicate',
            'reorder',
            'delete',
            'delete_any',
            'force_delete',
            'force_delete_any',
            // Step-specific approval permissions
            'approve_pending_requirements',
            'approve_initial',
            'approve_final',
            // License Requirements
            'accept_license_requirement',
            'reject_license_requirement',
            'ask_modification_license_requirement',
            'delete_license_requirement',
            'upload_license_requirement_file',
        ];
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('well_license.basic_information'))
                    ->schema(static::getBasicInformationFields())
                    ->columns(2),

                Forms\Components\Section::make(__('well_license.location_information'))
                    ->schema(static::getLocationInformationFields())
                    ->columns(2),

                Forms\Components\Section::make(__('well_license.well_specifications'))
                    ->schema(static::getWellSpecificationFields())
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('ID')
                    ->badge()
                    ->color('gray')
                    ->prefix('#')
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('well_name')
                    ->label(__('well_license.well_name'))
                    ->searchable()
                    ->sortable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->well_name)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('association.name')
                    ->label(__('well_license.association'))
                    ->searchable()
                    ->sortable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->association?->name)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('well_license.status'))
                    ->badge()
                    ->formatStateUsing(fn (LicenseStatus $state): string => $state->getLabel())
                    ->toggleable(),

                Tables\Columns\TextColumn::make('ministry_license_number')
                    ->label(__('well_license.ministry_license_number_column'))
                    ->badge()
                    ->color('success')
                    ->searchable()
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: false),

                Tables\Columns\TextColumn::make('state.name')
                    ->label(__('well_license.state'))
                    ->searchable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->state?->name)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('city.name')
                    ->label(__('well_license.city'))
                    ->searchable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->city?->name)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('well_license.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label(__('well_license.status'))
                    ->options(LicenseStatus::class),

                Tables\Filters\SelectFilter::make('state_id')
                    ->label(__('well_license.state'))
                    ->options(State::pluck('name', 'id')),
            ])
            ->headerActions([
                ExportAction::make()
                    ->exporter(WellLicenseExporter::class),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListWellLicenses::route('/'),
            'create' => Pages\CreateWellLicense::route('/create'),
            'view' => Pages\ViewWellLicense::route('/{record}'),
            'edit' => Pages\EditWellLicense::route('/{record}/edit'),
        ];
    }

    /**
     * Get the basic information form fields
     */
    public static function getBasicInformationFields(): array
    {
        return [
            Forms\Components\Select::make('association_id')
                ->label(__('well_license.association'))
                ->relationship('association', 'name')
                ->required()
                ->searchable()
                ->preload(),

            Forms\Components\TextInput::make('well_name')
                ->label(__('well_license.well_name'))
                ->required()
                ->maxLength(255),

            Forms\Components\Select::make('status')
                ->label(__('well_license.status'))
                ->options(LicenseStatus::class)
                ->default(LicenseStatus::PENDING_REQUIREMENTS)
                ->required()
                ->disabled(fn ($context) => $context === 'create'),

            Forms\Components\Hidden::make('created_by')
                ->default(fn () => Auth::id()),
        ];
    }

    /**
     * Get the location information form fields
     */
    public static function getLocationInformationFields(): array
    {
        return [
            Forms\Components\Select::make('state_id')
                ->label(__('well_license.state'))
                ->relationship(
                    'state',
                    'name',
                    fn (Builder $query, Get $get) => $query
                        ->orderByName()
                )
                ->required()
                ->searchable()
                ->preload()
                ->live()
                ->afterStateUpdated(function (Set $set) {
                    $set('city_id', null);
                    $set('center_id', null);
                })
                ->options(function (Get $get) {
                    return \App\Models\State::pluck('name', 'id');
                }),

            Forms\Components\Select::make('city_id')
                ->label(__('well_license.city'))
                ->relationship(
                    'city',
                    'name',
                    fn (Builder $query, Get $get) => $query
                        ->where('state_id', $get('state_id'))
                        ->orderByName()
                )
                ->required()
                ->searchable()
                ->preload()
                ->live()
                ->disabled(fn (Get $get) => ! $get('state_id'))
                ->afterStateUpdated(function (Set $set, $state) {
                    $set('center_id', null);

                    // Auto-update map location when city is selected
                    if ($state) {
                        $locationService = app(\App\Services\LocationCoordinatesService::class);
                        $coordinates = $locationService->getCityCoordinates($state);

                        if ($coordinates) {
                            $set('location', $coordinates);
                            $set('lat', $coordinates['lat']);
                            $set('lng', $coordinates['lng']);
                        }
                    }
                }),

            Forms\Components\Select::make('center_id')
                ->label(__('well_license.center'))
                ->relationship(
                    'center',
                    'name',
                    fn (Builder $query, Get $get) => $query
                        ->where('city_id', $get('city_id'))
                        ->orderByName()
                )
                ->required()
                ->searchable()
                ->preload()
                ->live()
                ->disabled(fn (Get $get) => ! $get('city_id'))
                ->helperText(fn (Get $get) => ! $get('city_id') ? __('well_license.select_city_first') : ''),

            Map::make('location')
                ->label(__('well_license.location_description'))
                ->mapControls([
                    'mapTypeControl' => true,
                    'scaleControl' => true,
                    'streetViewControl' => true,
                    'rotateControl' => true,
                    'fullscreenControl' => true,
                    'searchBoxControl' => false,
                    'zoomControl' => true,
                ])
                ->height(fn () => '400px')
                ->defaultZoom(8)
                ->defaultLocation([24.7136, 46.6753]) // Riyadh
                ->autocomplete('address')
                ->clickable(true)
                ->live()
                ->afterStateUpdated(function (Set $set, $state) {
                    if (is_array($state) && isset($state['lat']) && isset($state['lng'])) {
                        $set('lat', round($state['lat'], 8));
                        $set('lng', round($state['lng'], 8));
                    }
                })
                // ->afterStateHydrated(function (Set $set, $state, $record) {
                //     if ($record && $record->lat && $record->lng) {
                //         $set('location', [
                //             'lat' => (float) $record->lat,
                //             'lng' => (float) $record->lng,
                //         ]);
                //     }
                // })
                ->columnSpanFull(),

            Forms\Components\TextInput::make('lat')
                ->label(__('well_license.lat'))
                ->numeric()
                ->step(0.00000001)
                ->minValue(-90)
                ->maxValue(90)
                ->live()
                ->afterStateUpdated(callback: function (Set $set, $state, Get $get) {
                    $set('location', [
                        'lat' => (float) $state,
                        'lng' => (float) $get('lng'),
                    ]);
                })
                ->lazy(),

            Forms\Components\TextInput::make('lng')
                ->label(__('well_license.lng'))
                ->numeric()
                ->step(0.00000001)
                ->minValue(-180)
                ->maxValue(180)
                ->live()
                ->afterStateUpdated(function (Set $set, $state, Get $get) {
                    $set('location', [
                        'lat' => (float) $get('lat'),
                        'lng' => (float) $state,
                    ]);
                })
                ->lazy(),
        ];
    }

    /**
     * Get the well specification form fields
     */
    public static function getWellSpecificationFields(): array
    {
        return [
            Forms\Components\TextInput::make('well_depth')
                ->label(__('well_license.well_depth'))
                ->required()
                ->numeric()
                ->step(0.01)
                ->minValue(0)
                ->suffix(__('well_license.well_depth_suffix')),

            Forms\Components\TextInput::make('well_diameter')
                ->label(__('well_license.well_diameter'))
                ->numeric()
                ->step(0.01)
                ->minValue(0)
                ->suffix(__('well_license.well_diameter_suffix')),

            Forms\Components\TextInput::make('pump_size')
                ->label(__('well_license.pump_size'))
                ->numeric()
                ->step(0.01)
                ->minValue(0)
                ->suffix(__('well_license.pump_size_suffix')),

            Forms\Components\TextInput::make('withdrawal_amount')
                ->label(__('well_license.withdrawal_amount'))
                ->numeric()
                ->step(0.01)
                ->minValue(0)
                ->suffix(__('well_license.withdrawal_amount_suffix')),
        ];
    }
}
