<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ProjectCharterDeliverableResource\Pages;
use App\Models\ProjectCharter;
use App\Models\ProjectCharterDeliverable;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Pages\SubNavigationPosition;
use Filament\Resources\Pages\Page;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;

class ProjectCharterDeliverableResource extends Resource
{
    protected static ?string $model = ProjectCharterDeliverable::class;

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

    protected static ?int $navigationSort = 6;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

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

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

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('project_charter_deliverable.basic_information'))
                    ->schema([
                        Forms\Components\Select::make('project_charter_id')
                            ->label(__('project_charter_deliverable.project_charter'))
                            ->relationship('projectCharter', 'name')
                            ->required()
                            ->searchable()
                            ->preload()
                            ->reactive()
                            ->afterStateUpdated(function (callable $set, $state) {
                                // Clear the expected_delivery_date when project charter changes
                                // so user must re-select it within new constraints
                                $set('expected_delivery_date', null);
                            }),

                        Forms\Components\TextInput::make('name')
                            ->label(__('project_charter_deliverable.name'))
                            ->required()
                            ->maxLength(255),

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

                Forms\Components\Section::make(__('project_charter_deliverable.additional_details'))
                    ->schema([
                        Forms\Components\DatePicker::make('expected_delivery_date')
                            ->label(__('project_charter_deliverable.expected_delivery_date'))
                            ->reactive()
                            ->afterOrEqual(function (Get $get) {
                                $projectCharterId = $get('project_charter_id');
                                if ($projectCharterId) {
                                    $projectCharter = ProjectCharter::find($projectCharterId);

                                    return $projectCharter?->start_date;
                                }

                                return null;
                            })
                            ->beforeOrEqual(function (Get $get) {
                                $projectCharterId = $get('project_charter_id');
                                if ($projectCharterId) {
                                    $projectCharter = ProjectCharter::find($projectCharterId);

                                    return $projectCharter?->expected_end_date;
                                }

                                return null;
                            }),

                        Forms\Components\TextInput::make('payment_number')
                            ->label(__('project_charter_deliverable.payment_number'))
                            ->maxLength(255),

                        Forms\Components\TextInput::make('estimated_cost')
                            ->label(__('project_charter_deliverable.estimated_cost'))
                            ->numeric()
                            ->minValue(0)
                            ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                            ->step(0.01)
                            ->helperText(__('project_charter_deliverable.estimated_cost_helper')),

                        Forms\Components\TextInput::make('weight')
                            ->label(__('project_charter_deliverable.weight'))
                            ->numeric()
                            ->minValue(0)
                            ->maxValue(100)
                            ->suffix('%')
                            ->helperText(__('project_charter_deliverable.weight_helper')),
                    ])
                    ->columns(3),
            ]);
    }

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

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

                Tables\Columns\TextColumn::make('description')
                    ->label(__('project_charter_deliverable.description'))
                    ->limit(20)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('payment_number')
                    ->label(__('project_charter_deliverable.payment_number'))
                    ->sortable()
                    ->searchable()
                    ->toggleable(),

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

                Tables\Columns\TextColumn::make('weight')
                    ->label(__('project_charter_deliverable.weight'))
                    ->numeric()
                    ->sortable()
                    ->suffix('%')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('expected_delivery_date')
                    ->label(__('project_charter_deliverable.expected_delivery_date'))
                    ->date()
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('project_charter_deliverable.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('project_charter_id')
                    ->label(__('project_charter_deliverable.project_charter'))
                    ->relationship('projectCharter', 'name')
                    ->searchable()
                    ->preload(),
            ])
            ->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 [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProjectCharterDeliverables::route('/'),
            // 'create' => Pages\CreateProjectCharterDeliverable::route('/create'),
            // 'view' => Pages\ViewProjectCharterDeliverable::route('/{record}'),
            // 'edit' => Pages\EditProjectCharterDeliverable::route('/{record}/edit'),
            'manage_completion_reports' => Pages\ManageCompletionReports::route('/{record}/completion-reports'),
        ];
    }

    public static function getRecordSubNavigation(Page $page): array
    {
        return $page->generateNavigationItems([
            // Pages\ViewProjectCharterDeliverable::class,
            // Pages\ManageCompletionReports::class,
        ]);
    }
}
