<?php

namespace App\Filament\Resources\PerformanceCardResource\Pages;

use App\Filament\Resources\PerformanceCardResource;
use App\Models\Initiative;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Pages\ManageRelatedRecords;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;

class ViewInitiativesPerformanceCard extends ManageRelatedRecords
{
    protected static string $resource = PerformanceCardResource::class;

    protected static string $relationship = 'initiatives';

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

    public static function getNavigationLabel(): string
    {
        return __('initiative.initiatives');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('initiative.initiatives');
    }

    public function getTitle(): string
    {
        return __('initiative.initiatives');
    }

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

                Forms\Components\DatePicker::make('start_date')
                    ->label(__('initiative.start_date'))
                    ->required()
                    ->afterOrEqual(function (): ?\DateTime {
                        $wallet = $this->getOwnerRecord()->wallet;

                        return $wallet?->start_date;
                    })
                    ->beforeOrEqual(function (): ?\DateTime {
                        $wallet = $this->getOwnerRecord()->wallet;

                        return $wallet?->expected_end_date;
                    })
                    ->helperText(function (): string {
                        $wallet = $this->getOwnerRecord()->wallet;
                        if ($wallet && $wallet->start_date && $wallet->expected_end_date) {
                            return __('initiative.date_range_wallet_helper').' ('.
                                $wallet->start_date->format('M d, Y').' - '.
                                $wallet->expected_end_date->format('M d, Y').')';
                        }

                        return __('initiative.date_range_helper');
                    }),

                Forms\Components\DatePicker::make('expected_end_date')
                    ->label(__('initiative.expected_end_date'))
                    ->required()
                    ->after('start_date')
                    ->afterOrEqual(function (): ?\DateTime {
                        $wallet = $this->getOwnerRecord()->wallet;

                        return $wallet?->start_date;
                    })
                    ->beforeOrEqual(function (): ?\DateTime {
                        $wallet = $this->getOwnerRecord()->wallet;

                        return $wallet?->expected_end_date;
                    })
                    ->helperText(function (): string {
                        $wallet = $this->getOwnerRecord()->wallet;
                        if ($wallet && $wallet->start_date && $wallet->expected_end_date) {
                            return __('initiative.wallet_date_constraint').' ('.
                                $wallet->start_date->format('M d, Y').' - '.
                                $wallet->expected_end_date->format('M d, Y').')';
                        }

                        return __('initiative.must_be_after_start');
                    }),

                Forms\Components\Textarea::make('description')
                    ->label(__('initiative.description'))
                    ->rows(3)
                    ->maxLength(1000),

                Forms\Components\TextInput::make('expected_cost')
                    ->label(__('initiative.expected_cost'))
                    ->numeric()
                    ->step(0.01)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>')),

                Forms\Components\TextInput::make('emergency_reserve')
                    ->label(__('initiative.emergency_reserve'))
                    ->numeric()
                    ->step(0.01)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>')),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label(__('initiative.initiative_number'))
                    ->badge()
                    ->color('gray')
                    ->prefix('#')
                    ->sortable(),

                Tables\Columns\TextColumn::make('name')
                    ->label(__('initiative.name'))
                    ->searchable()
                    ->sortable()
                    ->weight('medium'),

                Tables\Columns\TextColumn::make('start_date')
                    ->label(__('initiative.start_date'))
                    ->date()
                    ->sortable()
                    ->icon('heroicon-o-calendar-days'),

                Tables\Columns\TextColumn::make('expected_end_date')
                    ->label(__('initiative.expected_end_date'))
                    ->date()
                    ->sortable()
                    ->icon('heroicon-o-calendar')
                    ->color('warning'),

                Tables\Columns\TextColumn::make('performanceCard.department.name')
                    ->label(__('initiative.department'))
                    ->searchable()
                    ->icon('heroicon-o-building-office')
                    ->color('primary'),

                Tables\Columns\TextColumn::make('expected_cost')
                    ->label(__('initiative.expected_cost'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('emergency_reserve')
                    ->label(__('initiative.emergency_reserve'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->toggleable(),
            ])
            ->filters([])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label(__('initiative.create_initiative'))
                    ->mutateFormDataUsing(function (array $data): array {
                        // Set the performance_wallet_id from the parent record
                        $data['performance_wallet_id'] = $this->getOwnerRecord()->wallet?->id;

                        return $data;
                    })
                    ->visible(fn () => $this->getOwnerRecord()->wallet !== null)
                    ->modalHeading(__('initiative.create_initiative'))
                    ->successNotificationTitle(__('initiative.created_successfully')),

                // Show info action when no wallet exists
                Tables\Actions\Action::make('no_wallet_info')
                    ->label(__('initiative.create_wallet_first'))
                    ->icon('heroicon-o-information-circle')
                    ->color('warning')
                    ->disabled()
                    ->visible(fn () => $this->getOwnerRecord()->wallet === null)
                    ->tooltip(__('initiative.wallet_required_tooltip')),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make()
                        ->url(fn (Initiative $record): string => \App\Filament\Resources\InitiativeResource::getUrl('view', ['record' => $record])),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }
}
