<?php

namespace App\Filament\Resources\Activities\RelationManagers;

use App\Models\MemberPoint;
use Filament\Actions\AttachAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DetachBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;

class ParticipantsRelationManager extends RelationManager
{
    protected static string $relationship = 'participants';
    protected static ?string $title = 'Kehadiran Peserta';

    public function form(Schema $schema): Schema
    {
        return $schema->components([
            Select::make('status')
                ->options(['hadir' => 'Hadir', 'izin' => 'Izin', 'alpha' => 'Alpha'])
                ->default('hadir')->required(),
            Textarea::make('notes')->label('Catatan')->rows(2),
        ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                TextColumn::make('name')->label('Anggota')->searchable(),
                TextColumn::make('pivot.status')->label('Status')->badge()
                    ->color(fn ($state) => match ($state) {
                        'hadir' => 'success',
                        'izin'  => 'warning',
                        'alpha' => 'danger',
                        default => 'gray',
                    }),
                TextColumn::make('pivot.notes')->label('Catatan')->placeholder('-'),
            ])
            ->headerActions([
                AttachAction::make()->preloadRecordSelect()
                    ->form(fn (AttachAction $action) => [
                        $action->getRecordSelect(),
                        Select::make('status')
                            ->options(['hadir' => 'Hadir', 'izin' => 'Izin', 'alpha' => 'Alpha'])
                            ->default('hadir')->required(),
                        Textarea::make('notes')->label('Catatan')->rows(2),
                    ])
                    ->after(function (AttachAction $action, array $data) {
                        if (($data['status'] ?? 'hadir') === 'hadir') {
                            $activity = $this->getOwnerRecord();
                            MemberPoint::firstOrCreate(
                                ['user_id' => $data['recordId'], 'source_type' => 'activity', 'source_id' => $activity->id],
                                ['points' => 10, 'reason' => "Hadir di kegiatan: {$activity->title}"]
                            );
                        }
                    }),
            ])
            ->recordActions([EditAction::make()])
            ->toolbarActions([BulkActionGroup::make([DetachBulkAction::make()])]);
    }
}
