<?php

namespace App\Filament\Resources\ProjectCharterResource\Pages;

use App\Filament\Resources\ProjectCharterResource;
use App\Models\RiskRegister;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Pages\ManageRelatedRecords;
use Filament\Tables;
use Filament\Tables\Table;

class ManageRiskRegisters extends ManageRelatedRecords
{
    protected static string $resource = ProjectCharterResource::class;

    protected static string $relationship = 'riskRegisters';

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

    public static function getNavigationLabel(): string
    {
        return __('risk_register.manage_risk_registers');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('risk_register.risk_registers');
    }

    public function getTitle(): string
    {
        return __('risk_register.risk_registers');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('risk_register.risk_assessment'))
                    ->description(__('risk_register.risk_assessment_description'))
                    ->schema([
                        Forms\Components\Select::make('incident_likelihood')
                            ->label(__('risk_register.incident_likelihood'))
                            ->options([
                                RiskRegister::LIKELIHOOD_LEVEL_LOW => __('risk_register.likelihood_low'),
                                RiskRegister::LIKELIHOOD_LEVEL_MEDIUM => __('risk_register.likelihood_medium'),
                                RiskRegister::LIKELIHOOD_LEVEL_HIGH => __('risk_register.likelihood_high'),
                            ])
                            ->placeholder(__('risk_register.incident_likelihood_placeholder'))
                            ->native(false)
                            ->live()
                            ->columnSpan(1),

                        Forms\Components\Select::make('impact_level')
                            ->label(__('risk_register.impact_level'))
                            ->options([
                                RiskRegister::IMPACT_LEVEL_LOW => __('risk_register.impact_low'),
                                RiskRegister::IMPACT_LEVEL_MEDIUM => __('risk_register.impact_medium'),
                                RiskRegister::IMPACT_LEVEL_HIGH => __('risk_register.impact_high'),
                            ])
                            ->placeholder(__('risk_register.impact_level_placeholder'))
                            ->native(false)
                            ->live()
                            ->columnSpan(1),

                        Forms\Components\Select::make('impact_on_cost')
                            ->label(__('risk_register.impact_on_cost'))
                            ->options([
                                'none' => __('risk_register.cost_impact_none'),
                                'minimal' => __('risk_register.cost_impact_minimal'),
                                'moderate' => __('risk_register.cost_impact_moderate'),
                                'significant' => __('risk_register.cost_impact_significant'),
                                'severe' => __('risk_register.cost_impact_severe'),
                            ])
                            ->placeholder(__('risk_register.impact_on_cost_placeholder'))
                            ->native(false)
                            ->columnSpan(1),

                        Forms\Components\Select::make('impact_on_time')
                            ->label(__('risk_register.impact_on_time'))
                            ->options([
                                'none' => __('risk_register.time_impact_none'),
                                'minimal' => __('risk_register.time_impact_minimal'),
                                'moderate' => __('risk_register.time_impact_moderate'),
                                'significant' => __('risk_register.time_impact_significant'),
                                'severe' => __('risk_register.time_impact_severe'),
                            ])
                            ->placeholder(__('risk_register.impact_on_time_placeholder'))
                            ->native(false)
                            ->columnSpan(1),
                    ])
                    ->columns(2),

                Forms\Components\Section::make(__('risk_register.mitigation_strategies'))
                    ->description(__('risk_register.mitigation_strategies_description'))
                    ->schema([
                        Forms\Components\Textarea::make('mitigation_plan')
                            ->label(__('risk_register.mitigation_plan'))
                            ->placeholder(__('risk_register.mitigation_plan_placeholder'))
                            ->rows(3)
                            ->maxLength(1000)
                            ->required(function (Forms\Get $get): bool {
                                return in_array($get('impact_level'), ['major', 'critical']);
                            })
                            ->columnSpanFull(),

                        Forms\Components\Textarea::make('contingency_plan')
                            ->label(__('risk_register.contingency_plan'))
                            ->placeholder(__('risk_register.contingency_plan_placeholder'))
                            ->rows(3)
                            ->maxLength(1000)
                            ->required(function (Forms\Get $get): bool {
                                return in_array($get('impact_level'), ['major', 'critical']);
                            })
                            ->columnSpanFull(),

                        Forms\Components\TextInput::make('financial_contingency')
                            ->label(__('risk_register.financial_contingency'))
                            ->placeholder(__('risk_register.financial_contingency_placeholder'))
                            ->numeric()
                            ->maxLength(500)
                            ->columnSpan(1),

                        Forms\Components\TextInput::make('technical_contingency')
                            ->label(__('risk_register.technical_contingency'))
                            ->placeholder(__('risk_register.technical_contingency_placeholder'))
                            ->numeric()
                            ->maxLength(500)
                            ->columnSpan(1),
                    ])
                    ->columns(2),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('incident_likelihood')
            ->columns([
                Tables\Columns\TextColumn::make('incident_likelihood')
                    ->label(__('risk_register.incident_likelihood'))
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        RiskRegister::LIKELIHOOD_LEVEL_LOW => __('risk_register.likelihood_low'),
                        RiskRegister::LIKELIHOOD_LEVEL_MEDIUM => __('risk_register.likelihood_medium'),
                        RiskRegister::LIKELIHOOD_LEVEL_HIGH => __('risk_register.likelihood_high'),
                        default => $state,
                    })
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        RiskRegister::LIKELIHOOD_LEVEL_LOW => 'success',
                        RiskRegister::LIKELIHOOD_LEVEL_MEDIUM => 'warning',
                        RiskRegister::LIKELIHOOD_LEVEL_HIGH => 'danger',
                        default => 'gray',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('impact_level')
                    ->label(__('risk_register.impact_level'))
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        RiskRegister::IMPACT_LEVEL_LOW => __('risk_register.impact_low'),
                        RiskRegister::IMPACT_LEVEL_MEDIUM => __('risk_register.impact_medium'),
                        RiskRegister::IMPACT_LEVEL_HIGH => __('risk_register.impact_high'),
                        default => $state,
                    })
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        RiskRegister::IMPACT_LEVEL_LOW => 'success',
                        RiskRegister::IMPACT_LEVEL_MEDIUM => 'warning',
                        RiskRegister::IMPACT_LEVEL_HIGH => 'danger',
                        default => 'gray',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('impact_on_cost')
                    ->label(__('risk_register.impact_on_cost'))
                    ->formatStateUsing(fn (?string $state): string => $state ? match ($state) {
                        'none' => __('risk_register.cost_impact_none'),
                        'minimal' => __('risk_register.cost_impact_minimal'),
                        'moderate' => __('risk_register.cost_impact_moderate'),
                        'significant' => __('risk_register.cost_impact_significant'),
                        'severe' => __('risk_register.cost_impact_severe'),
                        default => $state,
                    } : '-')
                    ->color(fn (?string $state): string => match ($state) {
                        'none' => 'success',
                        'minimal' => 'info',
                        'moderate' => 'warning',
                        'significant' => 'danger',
                        'severe' => 'danger',
                        default => 'gray',
                    })
                    ->toggleable(),

                Tables\Columns\TextColumn::make('impact_on_time')
                    ->label(__('risk_register.impact_on_time'))
                    ->formatStateUsing(fn (?string $state): string => $state ? match ($state) {
                        'none' => __('risk_register.time_impact_none'),
                        'minimal' => __('risk_register.time_impact_minimal'),
                        'moderate' => __('risk_register.time_impact_moderate'),
                        'significant' => __('risk_register.time_impact_significant'),
                        'severe' => __('risk_register.time_impact_severe'),
                        default => $state,
                    } : '-')
                    ->color(fn (?string $state): string => match ($state) {
                        'none' => 'success',
                        'minimal' => 'info',
                        'moderate' => 'warning',
                        'significant' => 'danger',
                        'severe' => 'danger',
                        default => 'gray',
                    })
                    ->toggleable(),

                Tables\Columns\TextColumn::make('mitigation_plan')
                    ->label(__('risk_register.mitigation_plan'))
                    ->limit(20)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        $state = $column->getState();
                        if (strlen($state) <= 50) {
                            return null;
                        }

                        return $state;
                    })
                    ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('risk_register.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('incident_likelihood')
                    ->label(__('risk_register.incident_likelihood'))
                    ->options([
                        'very_low' => __('risk_register.likelihood_very_low'),
                        'low' => __('risk_register.likelihood_low'),
                        'medium' => __('risk_register.likelihood_medium'),
                        'high' => __('risk_register.likelihood_high'),
                        'very_high' => __('risk_register.likelihood_very_high'),
                    ]),

                Tables\Filters\SelectFilter::make('impact_level')
                    ->label(__('risk_register.impact_level'))
                    ->options([
                        'negligible' => __('risk_register.impact_negligible'),
                        'minor' => __('risk_register.impact_minor'),
                        'moderate' => __('risk_register.impact_moderate'),
                        'major' => __('risk_register.impact_major'),
                        'critical' => __('risk_register.impact_critical'),
                    ]),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label(__('risk_register.risk_register'))
                    ->icon('heroicon-o-plus')
                    ->mutateFormDataUsing(function (array $data): array {
                        // Set the charter_id from the parent record
                        $data['charter_id'] = $this->getOwnerRecord()->id;

                        return $data;
                    })
                    ->successNotificationTitle(__('risk_register.created_successfully')),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make()
                        ->successNotificationTitle(__('risk_register.updated_successfully')),
                    Tables\Actions\DeleteAction::make()
                        ->successNotificationTitle(__('risk_register.deleted_successfully')),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->successNotificationTitle(__('risk_register.deleted_successfully')),
                ]),
            ])
            ->emptyStateIcon('heroicon-o-shield-check')
            ->emptyStateHeading(__('risk_register.no_risks_identified'))
            ->emptyStateActions([
                Tables\Actions\CreateAction::make()
                    ->label(__('risk_register.risk_register'))
                    ->icon('heroicon-o-plus')
                    ->mutateFormDataUsing(function (array $data): array {
                        $data['charter_id'] = $this->getOwnerRecord()->id;

                        return $data;
                    })
                    ->successNotificationTitle(__('risk_register.created_successfully')),
            ])
            ->defaultSort('created_at', 'desc');
    }
}
