<?php

namespace App\Filament\AssociationAdmin\Resources;

use App\Enums\LicenseStatus;
use App\Filament\AssociationAdmin\Resources\AssociationWellLicenseResource\Pages;
use App\Filament\Resources\WellLicenseResource as BaseWellLicenseResource;
use App\Models\WellLicense;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class AssociationWellLicenseResource 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 getNavigationLabel(): string
    {
        return __('well_license.well_licenses');
    }

    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',
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return WellLicense::query()
            ->withoutGlobalScope(\App\Scopes\ViewPermissionScope::class)
            ->where('association_id', Auth::user()->association_id ?? 0);
    }

    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(BaseWellLicenseResource::getLocationInformationFields())
                    ->columns(2),

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

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(function (Builder $query) {
                $user = Auth::user();
                if ($user && $user->association_id) {
                    $query->where('association_id', $user->association_id);
                } else {
                    // If user has no association, show no licenses for security
                    $query->whereRaw('1 = 0');
                }
            })
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('ID')
                    ->badge()
                    ->color('gray')
                    ->prefix('#')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('well_name')
                    ->label(__('well_license.well_name'))
                    ->searchable()
                    ->sortable(),

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

                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(),

                Tables\Columns\TextColumn::make('city.name')
                    ->label(__('well_license.city'))
                    ->searchable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('well_license.created_at'))
                    ->date()
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label(__('well_license.status'))
                    ->options(LicenseStatus::class),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                ]),
            ])
            ->bulkActions([
                // No bulk actions for association admin
            ])
            ->defaultSort('created_at', 'desc');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAssociationWellLicenses::route('/'),
            'create' => Pages\CreateAssociationWellLicense::route('/create'),
            'view' => Pages\ViewAssociationWellLicense::route('/{record}'),
        ];
    }

    /**
     * Get the basic information form fields
     */
    public static function getBasicInformationFields(): array
    {
        return [
            Forms\Components\Hidden::make('association_id')
                ->default(fn () => Auth::user()->association_id),

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

            Forms\Components\Hidden::make('status')
                ->default(LicenseStatus::INITIAL_APPROVAL),

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