<?php

namespace App\Filament\Resources\RequirementQuestions;

use App\Enums\UserRole;
use App\Filament\Resources\RequirementQuestions\Pages\ManageRequirementQuestions;
use App\Models\RequirementQuestion;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Gate;

class RequirementQuestionResource extends Resource
{
    protected static ?string $model = RequirementQuestion::class;

    protected static string|\UnitEnum|null $navigationGroup = 'Gestão do Projeto';

    protected static ?int $navigationSort = 3;

    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedQuestionMarkCircle;

    protected static ?string $recordTitleAttribute = 'question';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Select::make('project_id')->label('Projeto')->relationship('project', 'name')->searchable()->preload()->required(),
                Select::make('assigned_to_user_id')
                    ->label('Responsável principal')
                    ->relationship(
                        'assignee',
                        'name',
                        modifyQueryUsing: fn (Builder $query): Builder => $query->whereIn('role', [
                            UserRole::Admin->value,
                            UserRole::Collaborator->value,
                        ]),
                    )
                    ->searchable()
                    ->preload(),
                Textarea::make('question')->label('Pergunta')->required()->rows(3)->columnSpanFull(),
                Textarea::make('context')->label('Contexto')->rows(3)->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('project.name')->label('Projeto')->searchable()->sortable(),
                TextColumn::make('question')->label('Pergunta')->limit(80)->searchable()->wrap(),
                TextColumn::make('assignee.name')
                    ->label('Responsável principal')
                    ->placeholder('Não atribuída')
                    ->formatStateUsing(fn (?string $state, RequirementQuestion $record): string => $record->assigned_to_user_id === auth()->id()
                        ? "{$state} (você)"
                        : ($state ?? 'Não atribuída')),
                TextColumn::make('status')->label('Status')->formatStateUsing(fn (string $state): string => RequirementQuestion::STATUS_OPTIONS[$state] ?? $state)->badge(),
                TextColumn::make('answer')->label('Resposta')->limit(60)->placeholder('Aguardando resposta')->wrap(),
                TextColumn::make('answered_by')->label('Respondida por')->searchable(),
                TextColumn::make('answered_at')->label('Respondida em')->dateTime('d/m/Y H:i')->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')->label('Status')->options(RequirementQuestion::STATUS_OPTIONS),
                SelectFilter::make('assigned_to_user_id')->label('Responsável principal')->relationship('assignee', 'name'),
            ])
            ->modifyQueryUsing(fn (Builder $query): Builder => $query
                ->with('assignee')
                ->when(
                    auth()->id(),
                    fn (Builder $query, int $userId): Builder => $query->orderByRaw(
                        'CASE WHEN assigned_to_user_id = ? THEN 0 ELSE 1 END',
                        [$userId],
                    ),
                ))
            ->defaultSort('status')
            ->recordClasses(fn (RequirementQuestion $record): ?string => $record->assigned_to_user_id === auth()->id()
                ? 'onecheck-question-assigned'
                : null)
            ->recordActions([
                Action::make('answer')
                    ->label('Responder')
                    ->icon(Heroicon::OutlinedChatBubbleLeftRight)
                    ->authorize('answer')
                    ->schema([
                        Textarea::make('answer')
                            ->label('Resposta')
                            ->required()
                            ->rows(6),
                    ])
                    ->action(function (RequirementQuestion $record, array $data, Action $action): void {
                        Gate::authorize('answer', $record);

                        $record->answer($data['answer'], auth()->user());

                        $action->success();
                    })
                    ->successNotificationTitle('Resposta registrada'),
                EditAction::make()->authorize('update'),
                DeleteAction::make()->authorize('delete'),
            ]);
    }

    public static function getNavigationLabel(): string
    {
        return 'Perguntas de Requisitos';
    }

    public static function getModelLabel(): string
    {
        return 'pergunta de requisito';
    }

    public static function getPluralModelLabel(): string
    {
        return 'perguntas de requisitos';
    }

    public static function getPages(): array
    {
        return [
            'index' => ManageRequirementQuestions::route('/'),
        ];
    }
}
