<?php

declare(strict_types=1);

namespace App\Filament\Resources\Users;

use App\Enums\UserRole;
use App\Filament\Resources\Users\Pages\ListUsers;
use App\Filament\Resources\Users\Pages\ViewUser;
use App\Models\User;
use BackedEnum;
use Filament\Actions\ViewAction;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

/**
 * Artists and staff.
 *
 * Read-only by design. Editing a customer's details from here would let an
 * admin change the artist name that a live booking's payment reference was
 * derived from, which is precisely the string the studio is trying to match
 * against a bank statement.
 */
class UserResource extends Resource
{
    protected static ?string $model = User::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $navigationLabel = 'Artists';

    protected static ?int $navigationSort = 2;

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('profile.artist_name')
                    ->label('Artist')
                    ->searchable()
                    ->weight('bold')
                    ->description(fn (User $record) => $record->name)
                    ->placeholder('Profile not set up'),

                TextColumn::make('email')->searchable()->copyable(),

                TextColumn::make('profile.phone')->label('Phone')->placeholder('—')->toggleable(),

                TextColumn::make('profile.date_of_birth')
                    ->label('Age')
                    // Two products gate on this: Young Creators is 16 to 25,
                    // and the Birthday Experience needs a chaperone under 18.
                    ->formatStateUsing(fn ($state, User $record) => $record->profile?->age() ?? '—')
                    ->badge()
                    ->color(fn (User $record) => match (true) {
                        $record->profile?->age() === null => 'danger',
                        $record->profile->age() < 18 => 'warning',
                        default => 'gray',
                    })
                    ->alignCenter(),

                TextColumn::make('profile.completed_bookings_count')
                    ->label('Sessions')
                    ->badge()
                    ->color('gray')
                    ->sortable()
                    ->alignCenter(),

                TextColumn::make('bookings_count')
                    ->label('Bookings')
                    ->counts('bookings')
                    ->alignCenter()
                    ->toggleable(),

                TextColumn::make('role')->badge()->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('created_at')->label('Joined')->date('j M Y')->sortable()->toggleable(),
            ])
            ->filters([
                SelectFilter::make('role')->options(UserRole::class),
            ])
            ->recordActions([ViewAction::make()])
            ->toolbarActions([]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make('Profile')
                ->schema([
                    TextEntry::make('profile.artist_name')->label('Artist name')->placeholder('—'),
                    TextEntry::make('name')->label('Legal name'),
                    TextEntry::make('email')->copyable(),
                    TextEntry::make('profile.phone')->label('Phone')->copyable()->placeholder('—'),
                    TextEntry::make('profile.date_of_birth')->label('Date of birth')->date('j M Y')->placeholder('Not given'),
                    TextEntry::make('role')->badge(),
                    TextEntry::make('profile.genres.name')
                        ->label('Genres')
                        ->badge()
                        ->placeholder('None chosen'),
                    TextEntry::make('profile.bio')->label('Bio')->columnSpanFull()->placeholder('—'),
                ])
                ->columns(3),

            Section::make('Loyalty')
                ->schema([
                    TextEntry::make('profile.completed_bookings_count')
                        ->label('Sessions completed')
                        ->badge()
                        ->color('success'),
                    TextEntry::make('created_at')->label('Customer since')->date('j M Y'),
                ])
                ->columns(3),
        ]);
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['profile.genres']);
    }

    public static function canCreate(): bool
    {
        return false;
    }

    public static function getPages(): array
    {
        return [
            'index' => ListUsers::route('/'),
            'view' => ViewUser::route('/{record}'),
        ];
    }
}
