<?php

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

use App\Models\CommitteeMember;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;

class MembersRelationManager extends RelationManager
{
    protected static string $relationship = 'members';

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

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('user_id')
                    ->label('Member')
                    ->relationship('user', 'id', fn ($query) => $query->whereHas('associations', fn ($q) => $q->where('associations.id', \Filament\Facades\Filament::getTenant()->id)))
                    ->getOptionLabelFromRecordUsing(fn ($record) => trim($record->firstname . ' ' . $record->surname))
                    ->getSearchResultsUsing(function (string $search) {
                        return \App\Models\User::whereHas('associations', fn ($q) => $q->where('associations.id', \Filament\Facades\Filament::getTenant()->id))
                            ->where(fn ($q) => $q->where('firstname', 'like', "%{$search}%")
                                ->orWhere('surname', 'like', "%{$search}%")
                                ->orWhere('email', 'like', "%{$search}%"))
                            ->limit(50)
                            ->get()
                            ->mapWithKeys(fn ($user) => [
                                $user->id => trim($user->firstname . ' ' . $user->surname) . " ({$user->email})",
                            ]);
                    })
                    ->searchable()
                    ->preload()
                    ->required(),
                Forms\Components\Select::make('role')
                    ->options(CommitteeMember::ROLES)
                    ->required()
                    ->default(CommitteeMember::ROLE_MEMBER),
                Forms\Components\DatePicker::make('appointed_at')
                    ->default(now())
                    ->required(),
                Forms\Components\Textarea::make('notes')
                    ->maxLength(500)
                    ->columnSpanFull(),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.firstname')
                    ->label('Name')
                    ->formatStateUsing(fn ($record) => $record->user ? trim($record->user->firstname . ' ' . $record->user->surname) : '—')
                    ->searchable(),
                Tables\Columns\TextColumn::make('role')
                    ->badge()
                    ->formatStateUsing(fn (string $state) => CommitteeMember::ROLES[$state] ?? ucfirst(str_replace('_', ' ', $state)))
                    ->color(fn (string $state): string => match ($state) {
                        'chairperson' => 'success',
                        'vice_chairperson' => 'info',
                        'secretary' => 'warning',
                        'treasurer' => 'danger',
                        'member' => 'gray',
                        default => 'gray',
                    }),
                Tables\Columns\IconColumn::make('is_active')
                    ->boolean()
                    ->label('Active'),
                Tables\Columns\TextColumn::make('appointed_at')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('removed_at')
                    ->date()
                    ->sortable()
                    ->placeholder('—'),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Active Status'),
                Tables\Filters\SelectFilter::make('role')
                    ->options(CommitteeMember::ROLES),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label('Add Member'),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\Action::make('change_role')
                    ->label('Change Role')
                    ->icon('heroicon-o-arrow-path')
                    ->form([
                        Forms\Components\Select::make('role')
                            ->options(CommitteeMember::ROLES)
                            ->required(),
                    ])
                    ->action(fn (CommitteeMember $record, array $data) => $record->update(['role' => $data['role']])),
                Tables\Actions\Action::make('remove')
                    ->label('Remove')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->action(fn (CommitteeMember $record) => $record->update([
                        'is_active' => false,
                        'removed_at' => now(),
                    ]))
                    ->visible(fn (CommitteeMember $record) => $record->is_active),
                Tables\Actions\Action::make('reinstate')
                    ->label('Reinstate')
                    ->icon('heroicon-o-arrow-uturn-left')
                    ->color('success')
                    ->requiresConfirmation()
                    ->action(fn (CommitteeMember $record) => $record->update([
                        'is_active' => true,
                        'removed_at' => null,
                    ]))
                    ->visible(fn (CommitteeMember $record) => !$record->is_active),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('is_active', 'desc');
    }
}
