<?php

namespace App\Filament\Resources\InitiativeResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;

class ProjectsRelationManager extends RelationManager
{
    protected static string $relationship = 'projects';

    public static function getTitle(\Illuminate\Database\Eloquent\Model $ownerRecord, string $pageClass): string
    {
        return __('initiative_project.projects');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('initiative_project.projects');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('initiative_project.basic_information'))
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label(__('initiative_project.name'))
                            ->required()
                            ->maxLength(255),

                        Forms\Components\TextInput::make('weight')
                            ->label(__('initiative_project.weight'))
                            ->required()
                            ->numeric()
                            ->minValue(0.01)
                            ->maxValue(100)
                            ->suffix('%')
                            ->helperText(__('initiative_project.weight_helper'))
                            ->live(onBlur: true)
                            ->afterStateUpdated(function ($state, Forms\Get $get, Forms\Set $set, ?string $operation, ?object $record) {
                                if ($state && is_numeric($state)) {

                                    // Get current total weight (excluding current record if editing)
                                    $currentTotal = $this->getOwnerRecord()
                                        ->projects()
                                        ->when($record, fn ($query) => $query->where('id', '!=', $record->id))
                                        ->sum('weight');

                                    $newTotal = $currentTotal + (float) $state;
                                    $available = 100 - $currentTotal;

                                    if ($newTotal > 100) {
                                        $set('weight', $available > 0 ? $available : 0.01);

                                        \Filament\Notifications\Notification::make()
                                            ->title(__('initiative_project.weight_exceeded_title'))
                                            ->body(__('initiative_project.weight_exceeded_message', [
                                                'requested' => $state,
                                                'available' => $available,
                                                'current' => $currentTotal,
                                            ]))
                                            ->warning()
                                            ->send();
                                    }
                                }
                            }),
                    ])
                    ->columns(2),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label(__('initiative_project.name'))
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('weight')
                    ->label(__('initiative_project.weight'))
                    ->numeric()
                    ->sortable()
                    ->suffix('%')
                    ->summarize(
                        Tables\Columns\Summarizers\Sum::make()
                            ->label(__('initiative_project.total_weight'))
                            ->formatStateUsing(function ($state) {
                                $color = $state > 100 ? 'danger' : ($state == 100 ? 'success' : 'warning');

                                return new \Illuminate\Support\HtmlString(
                                    '<span class="text-'.$color.'-600 font-bold">'.number_format($state, 1).'%</span>'
                                );
                            })
                    ),

                Tables\Columns\IconColumn::make('projectCharter')
                    ->label(__('initiative_project.has_charter'))
                    ->boolean()
                    ->getStateUsing(fn ($record) => $record->projectCharter !== null),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('initiative_project.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->before(function (array $data) {

                        // Server-side validation for create action
                        $currentTotal = $this->getOwnerRecord()->projects()->sum('weight');
                        $newTotal = $currentTotal + ($data['weight'] ?? 0);

                        if ($newTotal > 100) {
                            $available = 100 - $currentTotal;
                            \Filament\Notifications\Notification::make()
                                ->title(__('initiative_project.weight_exceeded_title'))
                                ->body(__('initiative_project.weight_exceeded_message', [
                                    'current' => $currentTotal,
                                    'available' => $available,
                                    'requested' => $data['weight'],
                                ]))
                                ->danger()
                                ->send();

                            $this->halt();
                        }
                    }),
            ])
            ->actions([
                // Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make()
                    ->before(function (array $data, $record) {

                        // Server-side validation for edit action (excluding current record)
                        $currentTotal = $this->getOwnerRecord()
                            ->projects()
                            ->where('id', '!=', $record->id)
                            ->sum('weight');
                        $newTotal = $currentTotal + ($data['weight'] ?? 0);

                        if ($newTotal > 100) {
                            $available = 100 - $currentTotal;
                            \Filament\Notifications\Notification::make()
                                ->title(__('initiative_project.weight_exceeded_title'))
                                ->body(__('initiative_project.weight_exceeded_message', [
                                    'current' => $currentTotal,
                                    'available' => $available,
                                    'requested' => $data['weight'],
                                ]))
                                ->danger()
                                ->send();

                            $this->halt();
                        }
                    }),

                Tables\Actions\Action::make('view_charter')
                    ->label(__('project_charter.view_charter'))
                    ->icon('heroicon-o-document-text')
                    ->color('info')
                    ->url(fn ($record) => $record->projectCharter
                        ? \App\Filament\Resources\ProjectCharterResource::getUrl('view', ['record' => $record->projectCharter])
                        : null)
                    ->visible(fn ($record) => $record->projectCharter !== null),

                // Action to create a new project charter
                Tables\Actions\Action::make('create_charter')
                    ->label(__('project_charter.create_charter'))
                    ->icon('heroicon-o-plus')
                    ->color('primary')
                    ->url(fn ($record) => $record->projectCharter
                        ? \App\Filament\Resources\ProjectCharterResource::getUrl('edit', ['record' => $record->projectCharter])
                        : \App\Filament\Resources\ProjectCharterResource::getUrl('create', [
                            'initiative_project_id' => $record->id,
                            'project_manner' => $record->initiative?->performanceCard?->project_manner ?? 'DEVELOPMENTAL',
                        ]))
                    ->visible(fn ($record) => $record->projectCharter === null),

                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public function isReadOnly(): bool
    {
        return false;
    }
}
