<?php

namespace App\Filament\Association\Resources\CommitteeResource\RelationManagers;

use App\Models\CommitteeReport;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Notifications\Notification;

class ReportsRelationManager extends RelationManager
{
    protected static string $relationship = 'reports';

    protected static ?string $title = 'Committee Reports';

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('title')
                    ->required()
                    ->maxLength(255),
                Forms\Components\Select::make('report_type')
                    ->options(CommitteeReport::REPORT_TYPES)
                    ->required()
                    ->default(CommitteeReport::TYPE_PROGRESS),
                Forms\Components\RichEditor::make('body')
                    ->required()
                    ->columnSpanFull(),
                Forms\Components\FileUpload::make('file_path')
                    ->label('Attachment')
                    ->directory('committees/reports')
                    ->maxSize(10240)
                    ->acceptedFileTypes(['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/*']),
                Forms\Components\DateTimePicker::make('submitted_at')
                    ->default(now())
                    ->required(),
                Forms\Components\Hidden::make('submitted_by')
                    ->default(auth()->id()),
                Forms\Components\Hidden::make('status')
                    ->default(CommitteeReport::STATUS_APPROVED),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('title')
                    ->searchable()
                    ->sortable()
                    ->limit(50),
                Tables\Columns\TextColumn::make('report_type')
                    ->badge()
                    ->formatStateUsing(fn (string $state) => CommitteeReport::REPORT_TYPES[$state] ?? ucfirst($state))
                    ->color(fn (string $state): string => match ($state) {
                        'progress' => 'info',
                        'final' => 'success',
                        'financial' => 'warning',
                        'minutes' => 'gray',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->formatStateUsing(fn (string $state) => CommitteeReport::STATUSES[$state] ?? ucfirst($state))
                    ->color(fn (string $state): string => match ($state) {
                        'approved' => 'success',
                        'pending' => 'warning',
                        'rejected' => 'danger',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('submittedBy.firstname')
                    ->label('Submitted By')
                    ->formatStateUsing(fn ($record) => $record->submittedBy
                        ? trim($record->submittedBy->firstname . ' ' . $record->submittedBy->surname)
                        : '—'),
                Tables\Columns\IconColumn::make('file_path')
                    ->label('File')
                    ->boolean()
                    ->trueIcon('heroicon-o-paper-clip')
                    ->falseIcon('heroicon-o-minus'),
                Tables\Columns\TextColumn::make('submitted_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('report_type')
                    ->options(CommitteeReport::REPORT_TYPES),
                Tables\Filters\SelectFilter::make('status')
                    ->options(CommitteeReport::STATUSES),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label('Submit Report'),
            ])
            ->actions([
                Tables\Actions\Action::make('approve')
                    ->label('Approve')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->action(function (CommitteeReport $record): void {
                        $record->update([
                            'status' => CommitteeReport::STATUS_APPROVED,
                            'reviewed_by' => auth()->id(),
                            'reviewed_at' => now(),
                            'rejection_reason' => null,
                        ]);
                        Notification::make()
                            ->title('Report approved')
                            ->success()
                            ->send();
                    })
                    ->visible(fn (CommitteeReport $record) => $record->status === CommitteeReport::STATUS_PENDING),
                Tables\Actions\Action::make('reject')
                    ->label('Reject')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->form([
                        Forms\Components\Textarea::make('rejection_reason')
                            ->label('Reason for Rejection')
                            ->required()
                            ->maxLength(500),
                    ])
                    ->action(function (CommitteeReport $record, array $data): void {
                        $record->update([
                            'status' => CommitteeReport::STATUS_REJECTED,
                            'reviewed_by' => auth()->id(),
                            'reviewed_at' => now(),
                            'rejection_reason' => $data['rejection_reason'],
                        ]);
                        Notification::make()
                            ->title('Report rejected')
                            ->danger()
                            ->send();
                    })
                    ->visible(fn (CommitteeReport $record) => $record->status === CommitteeReport::STATUS_PENDING),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('submitted_at', 'desc');
    }
}
