<?php

namespace App\Filament\Resources\Users\Schemas;

use App\Models\Division;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;

class UserForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema->components([
            TextInput::make('name')->required(),
            TextInput::make('email')->email()->unique(ignoreRecord: true),
            TextInput::make('password')->password()->revealable()
                ->required(fn ($operation) => $operation === 'create')
                ->dehydrateStateUsing(fn ($state) => filled($state) ? bcrypt($state) : null)
                ->dehydrated(fn ($state) => filled($state)),
            TextInput::make('phone')->label('Telepon'),
            Textarea::make('address')->label('Alamat')->rows(2)->columnSpanFull(),
            Select::make('division_id')->label('Divisi')
                ->options(Division::pluck('name', 'id'))
                ->searchable(),
            Select::make('status')
                ->options(['aktif' => 'Aktif', 'nonaktif' => 'Nonaktif'])
                ->default('aktif')
                ->required()
                ->live(),
            Textarea::make('inactive_reason')->label('Alasan Nonaktif')
                ->visible(fn ($get) => $get('status') === 'nonaktif')
                ->required(fn ($get) => $get('status') === 'nonaktif')
                ->columnSpanFull(),
            DatePicker::make('last_activity_date')->label('Terakhir Aktif'),
            Select::make('roles')->relationship('roles', 'name')
                ->multiple()->preload()->label('Role')
                ->getOptionLabelFromRecordUsing(fn ($record) => $record->name)
                ->options(function () {
                    $user = auth()->user();
                    $query = \Spatie\Permission\Models\Role::query()
                        ->whereNotIn('name', ['super_admin', 'panel_user', 'anggota']);

                    if (! $user->can('AssignKoordinator')) {
                        $query->where('name', '!=', 'koordinator');
                    }

                    return $query->pluck('name', 'id');
                }),
        ]);
    }
}
