<?php

namespace App\Filament\Resources\Consultants\RelationManagers;

use App\Models\User;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;

class AssignmentsRelationManager extends RelationManager
{
    protected static string $relationship = 'assignments';

    protected static ?string $title = 'Assigned members';

    public function form(Schema $schema): Schema
    {
        return $schema->components([
            Select::make('user_id')
                ->label('Member')
                ->options(fn () => User::query()->orderBy('name')->limit(500)->pluck('name', 'id'))
                ->searchable()
                ->getSearchResultsUsing(fn (string $search) => User::query()
                    ->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->limit(30)
                    ->pluck('name', 'id'))
                ->required(),
            Select::make('status')
                ->options(['active' => 'Active', 'ended' => 'Ended'])
                ->default('active')
                ->required(),
            TextInput::make('note')
                ->placeholder('e.g. Matched after Financial Health Check, focus on debt plan')
                ->maxLength(255)
                ->columnSpanFull(),
        ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('user.name')->label('Member')->searchable(),
                TextColumn::make('user.email')->label('Email')->toggleable(),
                TextColumn::make('status')
                    ->badge()
                    ->color(fn (string $state) => $state === 'active' ? 'success' : 'gray'),
                TextColumn::make('note')->limit(40)->toggleable(),
                TextColumn::make('created_at')->since()->label('Assigned'),
            ])
            ->headerActions([
                CreateAction::make()
                    ->label('Assign member')
                    ->mutateDataUsing(fn (array $data) => [...$data, 'assigned_by' => auth()->id()]),
            ])
            ->recordActions([EditAction::make(), DeleteAction::make()]);
    }
}
