<?php

namespace App\Filament\Construction\Resources;

use App\Filament\Construction\Concerns\AuthorizesConstructionResource;
use App\Filament\Construction\Resources\MilestoneResource\Pages;
use App\Models\Milestone;
use App\Models\Project;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Navigation\NavigationItem;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class MilestoneResource extends Resource
{
    use AuthorizesConstructionResource;

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

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

    protected static ?string $navigationGroup = 'Projects';

    protected static ?int $navigationSort = 2;

    protected static ?string $slug = 'projects/{project}/milestones';

    public static ?Project $parentProject = null;

    public static function shouldRegisterNavigation(): bool
    {
        return static::canViewAny();
    }

    public static function getNavigationItems(): array
    {
        return [
            NavigationItem::make(static::getNavigationLabel())
                ->group(static::getNavigationGroup())
                ->icon(static::getNavigationIcon())
                ->sort(static::getNavigationSort())
                ->url(static::getNavigationUrl())
                ->isActiveWhen(fn (): bool => request()->routeIs(static::getRouteBaseName() . '.*')),
        ];
    }

    public static function getNavigationUrl(): string
    {
        $projectId = Project::query()->orderBy('name')->value('id');

        return $projectId
            ? static::getUrl('index', ['project' => $projectId])
            : ProjectResource::getUrl('index');
    }

    protected static function viewPermission(): string
    {
        return 'cn_view_projects';
    }

    protected static function managePermission(): string
    {
        return 'cn_manage_projects';
    }

    public static function getNavigationLabel(): string
    {
        return 'Milestones';
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make()->schema([
                Forms\Components\Select::make('project_id')
                    ->relationship('project', 'name')
                    ->required()
                    ->searchable()
                    ->preload()
                    ->default(fn (): ?int => static::getParentProject()?->id),
                Forms\Components\TextInput::make('name')
                    ->required()
                    ->maxLength(255),
                Forms\Components\Select::make('stage')
                    ->options([
                        'excavation' => 'Excavation',
                        'foundation' => 'Foundation',
                        'structure' => 'Structure',
                        'roofing' => 'Roofing',
                        'finishing' => 'Finishing',
                        'completed' => 'Completed',
                    ])
                    ->default('excavation')
                    ->required(),
                Forms\Components\TextInput::make('completion_percentage')
                    ->numeric()
                    ->minValue(0)
                    ->maxValue(100)
                    ->suffix('%')
                    ->default(0)
                    ->required(),
                Forms\Components\DatePicker::make('target_date'),
                Forms\Components\DatePicker::make('completed_at'),
            ])->columns(2),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('project.name')
                    ->searchable()
                    ->sortable()
                    ->hidden(fn (): bool => static::getParentProject() !== null),
                Tables\Columns\TextColumn::make('stage')
                    ->badge()
                    ->sortable(),
                Tables\Columns\TextColumn::make('completion_percentage')
                    ->suffix('%')
                    ->sortable(),
                Tables\Columns\TextColumn::make('target_date')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('completed_at')
                    ->date()
                    ->sortable()
                    ->toggleable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('project')
                    ->relationship('project', 'name')
                    ->searchable()
                    ->preload()
                    ->hidden(fn (): bool => static::getParentProject() !== null),
                Tables\Filters\SelectFilter::make('stage')
                    ->options([
                        'excavation' => 'Excavation',
                        'foundation' => 'Foundation',
                        'structure' => 'Structure',
                        'roofing' => 'Roofing',
                        'finishing' => 'Finishing',
                        'completed' => 'Completed',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        if ($project = static::getParentProject()) {
            $query->where('project_id', $project->id);
        }

        return $query;
    }

    public static function getParentProject(): ?Project
    {
        $project = request()->route('project');

        if ($project !== null) {
            return $project instanceof Project ? $project : Project::find($project);
        }

        return static::$parentProject;
    }

    public static function resolveParentProject(): Project
    {
        return static::getParentProject() ?? abort(404);
    }

    public static function getUrl(string $name = 'index', array $parameters = [], bool $isAbsolute = true, ?string $panel = null, ?\Illuminate\Database\Eloquent\Model $tenant = null): string
    {
        if (! isset($parameters['project'])) {
            $project = static::getParentProject();

            if ($project) {
                $parameters['project'] = $project;
            }
        }

        return parent::getUrl($name, $parameters, $isAbsolute, $panel, $tenant);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListMilestones::route('/'),
            'create' => Pages\CreateMilestone::route('/create'),
            'edit' => Pages\EditMilestone::route('/{record}/edit'),
        ];
    }
}
