<?php

namespace App\Filament\AssociationAdmin\Resources\AssociationProjectCharterResource\RelationManagers;

use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\HtmlString;

class AssociationTasksRelationManager extends RelationManager
{
    protected static string $relationship = 'tasks';

    protected static ?string $recordTitleAttribute = 'name';

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

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

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

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

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->defaultGroup(
                Group::make('deliverable.name')
                    ->titlePrefixedWithLabel(false)
                    ->getTitleFromRecordUsing(fn ($record): string => __('project_charter.task_for_deliverable').': '.$record->deliverable->name)
                    ->getDescriptionFromRecordUsing(fn ($record): string => __('project_charter.progress').': '.$record->deliverable->progress_percentage.'%')
                    ->collapsible(),
            )
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label(__('project_charter.task_name'))
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('project_charter.status'))
                    ->badge()
                    ->color(fn ($record) => $record->status_color)
                    ->formatStateUsing(function ($state) {
                        return match ($state) {
                            'not_started' => __('project_charter.task_status_not_started'),
                            'in_progress' => __('project_charter.task_status_in_progress'),
                            'late' => __('project_charter.task_status_late'),
                            'done' => __('project_charter.task_status_done'),
                            default => $state,
                        };
                    })
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('end_date')
                    ->label(__('project_charter.expected_end_date'))
                    ->date()
                    ->sortable()
                    ->color(function ($record) {
                        if ($record->is_overdue) {
                            return 'danger';
                        }

                        return null;
                    }),

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

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

                Tables\Columns\TextColumn::make('progress_percentage')
                    ->label(__('project_charter.progress'))
                    ->formatStateUsing(fn ($state) => $state.'%')
                    ->badge()
                    ->color(fn ($state) => match (true) {
                        $state >= 100 => 'success',
                        $state >= 75 => 'warning',
                        $state >= 50 => 'info',
                        $state > 0 => 'gray',
                        default => 'secondary',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('project_charter.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('project_charter_deliverable_id')
                    ->label(__('project_charter.deliverable'))
                    ->relationship('deliverable', 'name'),

                Tables\Filters\Filter::make('overdue')
                    ->label(__('project_charter.overdue_tasks'))
                    ->query(fn (Builder $query) => $query->whereDate('end_date', '<', now())->where('progress_percentage', '<', 100)),

                Tables\Filters\Filter::make('completed')
                    ->label(__('project_charter.completed_tasks'))
                    ->query(fn (Builder $query) => $query->where('progress_percentage', '>=', 100)),

                Tables\Filters\Filter::make('in_progress')
                    ->label(__('project_charter.in_progress_tasks'))
                    ->query(fn (Builder $query) => $query->where('progress_percentage', '>', 0)->where('progress_percentage', '<', 100)),
            ])
            ->headerActions([
                // No create action for association admin
            ])
            ->actions([
                // Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([
                // No bulk actions for association admin
            ])
            ->defaultSort('end_date', 'asc')
            ->emptyStateIcon('heroicon-o-clipboard-document-list')
            ->emptyStateHeading(__('project_charter.no_tasks'));
    }

    public function isReadOnly(): bool
    {
        return true; // Association admin can only view tasks
    }

    protected function canCreate(): bool
    {
        return false;
    }

    protected function canEdit(\Illuminate\Database\Eloquent\Model $record): bool
    {
        return false;
    }

    protected function canDelete(\Illuminate\Database\Eloquent\Model $record): bool
    {
        return false;
    }
}
