<?php

namespace App\Filament\Resources;

use App\Filament\Resources\InitiativeResource\Pages;
use App\Filament\Resources\InitiativeResource\RelationManagers;
use App\Models\Initiative;
use App\Models\PerformanceWallet;
use App\Models\SekayaValue;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString;

class InitiativeResource extends Resource
{
    protected static ?string $model = Initiative::class;

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

    protected static ?int $navigationSort = 3;

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

    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 static function form(Form $form): Form
    {
        $user = Auth::user();

        return $form
            ->schema([
                Forms\Components\Section::make(__('initiative.basic_information'))
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label(__('initiative.name'))
                            ->required()
                            ->maxLength(255)
                            ->helperText(__('initiative.name_helper')),

                        Forms\Components\DatePicker::make('start_date')
                            ->label(__('initiative.start_date'))
                            ->required()
                            ->helperText(__('initiative.date_range_helper'))
                            ->reactive()
                            ->afterOrEqual(function (Get $get) {
                                $walletId = $get('performance_wallet_id');
                                if ($walletId) {
                                    $wallet = PerformanceWallet::find($walletId);

                                    return $wallet?->start_date;
                                }

                                return null;
                            })
                            ->beforeOrEqual(function (Get $get) {
                                $walletId = $get('performance_wallet_id');
                                if ($walletId) {
                                    $wallet = PerformanceWallet::find($walletId);

                                    return $wallet?->expected_end_date;
                                }

                                return null;
                            }),

                        Forms\Components\DatePicker::make('expected_end_date')
                            ->label(__('initiative.expected_end_date'))
                            ->required()
                            ->after('start_date')
                            ->reactive()
                            ->afterOrEqual(function (Get $get) {
                                $walletId = $get('performance_wallet_id');
                                if ($walletId) {
                                    $wallet = PerformanceWallet::find($walletId);

                                    return $wallet?->start_date;
                                }

                                return null;
                            })
                            ->beforeOrEqual(function (Get $get) {
                                $walletId = $get('performance_wallet_id');
                                if ($walletId) {
                                    $wallet = PerformanceWallet::find($walletId);

                                    return $wallet?->expected_end_date;
                                }

                                return null;
                            }),

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

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

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

                Forms\Components\Section::make(__('initiative.relationships'))
                    ->schema([
                        Forms\Components\Select::make('performance_wallet_id')
                            ->label(__('initiative.performance_wallet'))
                            ->relationship('performanceWallet', 'name')
                            ->required()
                            ->preload()
                            ->searchable()
                            ->helperText(__('initiative.performance_wallet_helper'))
                            ->reactive()
                            ->afterStateUpdated(function (callable $set, $state) {
                                $set('products', null);
                                // Clear the dates when wallet changes so user must re-select them within new constraints
                                $set('start_date', null);
                                $set('expected_end_date', null);
                            }),

                        Forms\Components\Select::make('products')
                            ->label(__('initiative.products'))
                            ->multiple()
                            ->relationship(
                                'products',
                                'name',
                                fn (Builder $query, Get $get) => $query
                                    ->where('type', SekayaValue::TYPE_PERFORMANCE_CARD_PRODUCT)
                                    ->when(
                                        $get('performance_wallet_id'),
                                        fn (Builder $query, $walletId) => $query->whereHas('performanceCards', function ($q) use ($walletId) {
                                            $q->where('id', function ($subQuery) use ($walletId) {
                                                $subQuery->select('performance_card_id')
                                                    ->from('performance_wallets')
                                                    ->where('id', $walletId)
                                                    ->limit(1);
                                            });
                                        })
                                    )
                            )
                            ->preload()
                            ->searchable()
                            ->helperText(__('initiative.products_helper'))
                            ->reactive(),

                        // Created By selector only for admins
                        Forms\Components\Select::make('created_by')
                            ->label(__('initiative.created_by'))
                            ->options(User::whereNull('association_id')->pluck('name', 'id'))
                            ->required()
                            ->visible(fn () => $user && $user->hasRole('admin')),

                        // For non-admins, set created_by automatically
                        Forms\Components\Hidden::make('created_by')
                            ->default(fn () => $user?->id)
                            ->visible(fn () => $user && ! $user->hasRole('admin')),
                    ])
                    ->columns(1),
            ]);
    }

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

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

                Tables\Columns\TextColumn::make('start_date')
                    ->label(__('initiative.start_date'))
                    ->date()
                    ->sortable(),

                Tables\Columns\TextColumn::make('expected_end_date')
                    ->label(__('initiative.expected_end_date'))
                    ->date()
                    ->sortable(),

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

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

                Tables\Columns\TextColumn::make('products_count')
                    ->label(__('initiative.products_count'))
                    ->counts('products')
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('created_at')
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('performance_wallet_id')
                    ->label(__('initiative.performance_wallet'))
                    ->relationship('performanceWallet', 'name')
                    ->preload(),

                Tables\Filters\Filter::make('date_range')
                    ->form([
                        Forms\Components\DatePicker::make('start_date_from'),
                        Forms\Components\DatePicker::make('start_date_until'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['start_date_from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('start_date', '>=', $date),
                            )
                            ->when(
                                $data['start_date_until'],
                                fn (Builder $query, $date): Builder => $query->whereDate('start_date', '<=', $date),
                            );
                    }),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [
            // RelationManagers\OperationGoalsRelationManager::class,
            // RelationManagers\ResultsRelationManager::class,
            RelationManagers\ProjectsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListInitiatives::route('/'),
            'create' => Pages\CreateInitiative::route('/create'),
            'view' => Pages\ViewInitiative::route('/{record}'),
            'edit' => Pages\EditInitiative::route('/{record}/edit'),
        ];
    }
}
