<?php

namespace App\Filament\Resources\Activities\RelationManagers;

use App\Models\MemberPoint;
use Filament\Actions\AttachAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DetachAction;
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()
                    ->visible(fn () => $this->getOwnerRecord()->status === 'approved')
                    ->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()
                    ->after(function (EditAction $action, $record, array $data) {
                        $activity = $this->getOwnerRecord();
                        $existing = MemberPoint::where('user_id', $record->id)
                            ->where('source_type', 'activity')
                            ->where('source_id', $activity->id)
                            ->first();

                        if (($data['status'] ?? 'hadir') === 'hadir' && ! $existing) {
                            MemberPoint::create([
                                'user_id'     => $record->id,
                                'points'      => 10,
                                'reason'      => "Hadir di kegiatan: {$activity->title}",
                                'source_type' => 'activity',
                                'source_id'   => $activity->id,
                            ]);
                        } elseif (($data['status'] ?? 'hadir') !== 'hadir' && $existing) {
                            $existing->delete();
                        }
                    }),
                DetachAction::make()
                    ->after(function ($record) {
                        $activity = $this->getOwnerRecord();
                        MemberPoint::where('user_id', $record->id)
                            ->where('source_type', 'activity')
                            ->where('source_id', $activity->id)
                            ->delete();
                    }),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DetachBulkAction::make()
                        ->after(function ($records) {
                            $activity = $this->getOwnerRecord();
                            MemberPoint::where('source_type', 'activity')
                                ->where('source_id', $activity->id)
                                ->whereIn('user_id', $records->pluck('id'))
                                ->delete();
                        }),
                ]),
            ]);
    }
}
