<?php

namespace App\Filament\Admin\Resources\ProjectCharters\RelationManagers;

use Filament\Actions\AssociateAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\DissociateAction;
use Filament\Actions\DissociateBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\HtmlString;

class DeliverablesRelationManager extends RelationManager
{
    protected static string $relationship = 'deliverables';

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->label(__('project_charter_deliverable.name'))
                    ->required()
                    ->maxLength(255),

                DatePicker::make('delivery_date')
                    ->label(__('project_charter_deliverable.delivery_date'))
                    ->required()
                    ->afterOrEqual(function () {
                        // Access the ProjectCharter (owner record) start_date
                        return $this->getOwnerRecord()->start_date;
                    })
                    ->beforeOrEqual(function () {
                        // Access the ProjectCharter (owner record) expected_end_date
                        return $this->getOwnerRecord()->expected_end_date;
                    }),

                TextInput::make('cost')
                    ->label(__('project_charter_deliverable.cost'))
                    ->numeric()
                    ->minValue(0)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->step(0.01)
                    ->reactive()
                    ->helperText(function (Get $get) {
                        $charter = $this->getOwnerRecord();
                        if (! $charter || ! $charter->cost) {
                            return __('project_charter_deliverable.cost_helper');
                        }

                        $currentTotal = $charter->deliverables()->sum('cost') ?? 0;
                        $available = $charter->cost - $currentTotal;

                        return __('project_charter_deliverable.cost_helper').' '.
                            __('project_charter.available_budget_info', [
                                'charter_cost' => number_format($charter->cost, 2),
                                'current_total' => number_format($currentTotal, 2),
                                'available' => number_format(max(0, $available), 2),
                            ]);
                    }),

                SpatieMediaLibraryFileUpload::make('deliverable_file')
                    ->label(__('project_charter_deliverable.file'))
                    ->collection('deliverable_file')
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(10240) // 10MB
                    ->downloadable()
                    ->helperText(__('project_charter_deliverable.file_helper'))
                    ->visible(fn ($operation) => $operation === 'edit') // Only show in edit mode
                    ->reactive(),
            ]);
    }

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

                TextColumn::make('delivery_date')
                    ->label(__('project_charter_deliverable.delivery_date'))
                    ->date('d M Y')
                    ->sortable(),

                TextColumn::make('cost')
                    ->label(__('project_charter_deliverable.cost'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->icon('heroicon-o-banknotes')
                    ->color('primary'),

                IconColumn::make('has_file')
                    ->label(__('project_charter_deliverable.has_file'))
                    ->boolean()
                    ->state(fn ($record) => $record->hasFile())
                    ->toggleable(),

                TextColumn::make('created_at')
                    ->label(__('project_charter_deliverable.created_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                TrashedFilter::make(),
            ])
            ->headerActions([
                CreateAction::make(),
                AssociateAction::make(),
            ])
            ->recordActions([
                EditAction::make(),
                DissociateAction::make(),
                DeleteAction::make(),
                ForceDeleteAction::make(),
                RestoreAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DissociateBulkAction::make(),
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ])
            ->modifyQueryUsing(fn (Builder $query) => $query
                ->withoutGlobalScopes([
                    SoftDeletingScope::class,
                ]));
    }

    public static function getTitle(Model $ownerRecord, string $pageClass): string
    {
        return __('project_charter_deliverable.deliverables');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('project_charter_deliverable.deliverables');
    }

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