<?php

namespace App\Filament\AssociationAdmin\Resources;

use App\Enums\AssociationType;
use App\Filament\AssociationAdmin\Resources\AssociationProjectCharterResource\Pages;
use App\Filament\AssociationAdmin\Resources\AssociationProjectCharterResource\RelationManagers;
use App\Models\ProjectCharter;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms\Form;
use Filament\Pages\SubNavigationPosition;
use Filament\Resources\Pages\Page;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\HtmlString;

class AssociationProjectCharterResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = ProjectCharter::class;

    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static ?int $navigationSort = 2;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

    public static function getNavigationLabel(): string
    {
        return __('project_charter.project_charters');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('project_charter.project_charters');
    }

    // use withoutGlobalScope(App\Scopes\ViewPermissionScope::class) using get elequent
    public static function getEloquentQuery(): Builder
    {
        return ProjectCharter::query()->withoutGlobalScope(\App\Scopes\ViewPermissionScope::class);
    }

    public static function form(Form $form): Form
    {
        // Read-only form - no form needed for association admin
        return $form->schema([]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(function (Builder $query) {
                $user = Auth::user();
                if ($user && $user->association_id) {
                    Log::info('AssociationProjectCharterResource: Filtering charters for association ID: '.$user->association_id);
                    $query->whereHas('order', function ($orderQuery) use ($user) {
                        $orderQuery->where('association_id', $user->association_id);
                    });
                } else {
                    // If user has no association, show no charters for security
                    $query->whereRaw('1 = 0');
                }
            })
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label(__('project_charter.name'))
                    ->sortable()
                    ->searchable(),

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

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

                Tables\Columns\TextColumn::make('estimated_cost')
                    ->label(__('project_charter.estimated_cost'))
                    ->numeric(2)
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('order.id')
                    ->label(__('project_charter.linked_order'))
                    ->sortable()
                    ->searchable()
                    ->formatStateUsing(fn ($record) => $record->order ? "#{$record->order->id} - ".(\App\Models\Order::getOrderTypes()[$record->order->type] ?? $record->order->type) : '-')
                    ->placeholder('-'),

                Tables\Columns\BadgeColumn::make('status')
                    ->label(__('project_charter.status'))
                    ->colors([
                        ProjectCharter::STATUS_APPROVED => 'success',
                    ])
                    ->formatStateUsing(fn (string $state): string => __(ProjectCharter::getStatuses()[$state] ?? $state)),

                Tables\Columns\TextColumn::make('deliverables_count')
                    ->label(__('project_charter.deliverables_count'))
                    ->counts('deliverables')
                    ->badge()
                    ->color('success'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('common.created_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('order')
                    ->relationship('order', 'id', function (Builder $query) {
                        $user = Auth::user();
                        if ($user && $user->association_id) {
                            $query->where('association_id', $user->association_id);
                        }
                    })
                    ->getOptionLabelFromRecordUsing(fn ($record) => "#{$record->id} - {$record->type}")
                    ->label(__('project_charter.linked_order')),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\Action::make('view_progress')
                        ->label(__('project_charter.view_progress'))
                        ->icon('heroicon-o-chart-bar')
                        ->color('info')
                        ->url(fn (ProjectCharter $record): string => static::getUrl('view_progress', ['record' => $record]))
                        ->visible(true), // Always show for approved charters
                ]),
            ])
            ->bulkActions([
                // No bulk actions for association admin
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\AssociationDeliverablesRelationManager::class,
            RelationManagers\AssociationTasksRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAssociationProjectCharters::route('/'),
            'view' => Pages\ViewAssociationProjectCharter::route('/{record}'),
            'view_progress' => Pages\ViewAssociationProjectCharterProgress::route('/{record}/progress'),
            'manage_files' => Pages\ManageAssociationProjectCharterFiles::route('/{record}/files'),
        ];
    }

    public static function getRecordSubNavigation(Page $page): array
    {
        $navigationItems = [
            Pages\ViewAssociationProjectCharter::class,
            Pages\ViewAssociationProjectCharterProgress::class,
            Pages\ManageAssociationProjectCharterFiles::class,
        ];

        return $page->generateNavigationItems($navigationItems);
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            // No create, update, delete permissions for association admin
        ];
    }

    public static function canAccess(): bool
    {
        $association = Auth::user()->association;
        if ($association->type !== AssociationType::ASSOCIATION) {
            return false;
        }

        return static::canViewAny();
    }
}
