<?php

namespace App\Filament\AssociationAdmin\Resources;

use App\Enums\LicenseStatus;
use App\Filament\AssociationAdmin\Resources\AssociationStationLicenseResource\Pages;
use App\Filament\Resources\StationLicenseResource as BaseStationLicenseResource;
use App\Models\StationLicense;
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 AssociationStationLicenseResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = StationLicense::class;

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

    protected static ?int $navigationSort = 2;

    public static function getNavigationLabel(): string
    {
        return __('station_license.station_licenses');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('station_license.station_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 StationLicense::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(__('station_license.basic_information'))
                    ->schema(static::getBasicInformationFields())
                    ->columns(2),

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

                Forms\Components\Section::make(__('station_license.station_specifications'))
                    ->schema(BaseStationLicenseResource::getStationSpecificationFields())
                    ->columns(2),

                Forms\Components\Section::make(__('station_license.environmental_compliance'))
                    ->schema(BaseStationLicenseResource::getEnvironmentalComplianceFields())
                    ->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('station_name')
                    ->label(__('station_license.station_name'))
                    ->searchable()
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('wellLicenses.well_name')
                    ->label(__('station_license.well_licenses'))
                    ->badge()
                    ->color('info')
                    ->searchable()
                    ->separator(',')
                    ->limit(20)
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: false),

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

                Tables\Columns\TextColumn::make('design_capacity')
                    ->label(__('station_license.design_capacity'))
                    ->numeric()
                    ->suffix(' m³/day'),

                Tables\Columns\IconColumn::make('has_environmental_permit')
                    ->label(__('station_license.has_environmental_permit'))
                    ->boolean(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('station_license.created_at'))
                    ->date()
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label(__('station_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 [
            AssociationStationLicenseResource\RelationManagers\RequirementsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAssociationStationLicenses::route('/'),
            'create' => Pages\CreateAssociationStationLicense::route('/create'),
            'view' => Pages\ViewAssociationStationLicense::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('station_name')
                ->label(__('station_license.station_name'))
                ->required()
                ->maxLength(255),

            Forms\Components\Select::make('wellLicenses')
                ->label(__('station_license.well_licenses'))
                ->relationship(
                    'wellLicenses',
                    'well_name',
                    fn (Builder $query) => $query
                        ->where('association_id', Auth::user()->association_id ?? 0)
                        ->where('status', LicenseStatus::APPROVED)
                        ->orderBy('well_name')
                )
                ->multiple()
                ->searchable()
                ->preload()
                ->required()
                ->helperText(__('station_license.well_licenses_helper')),

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

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