<?php

namespace App\Filament\Central\Resources;

use App\Filament\Central\Resources\CentralAdminResource\Pages\CreateCentralAdmin;
use App\Filament\Central\Resources\CentralAdminResource\Pages\EditCentralAdmin;
use App\Filament\Central\Resources\CentralAdminResource\Pages\ListCentralAdmins;
use App\Models\Central\CentralAdmin;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;

/**
 * Master-control operator accounts. The source app never had a UI for this —
 * `docs/MASTER_CONTROL.md` "Adding New Central Admins (Production)" is
 * explicitly `php artisan central:make-admin`, CLI-only, and
 * `Central\CentralAdminController` does not exist. This is new UI over an
 * existing, fully-functional model (App\Models\Central\CentralAdmin) and the
 * exact fields/semantics that command and model already define — not a port
 * of a controller, since none exists — built because the tenant side gained
 * its own Users/Roles screens in this same pass and master control had no
 * equivalent way to manage who can operate it without shelling in.
 *
 * No permission layer: `CentralAdmin` has none in the source (flat
 * `is_active`, no roles) — any authenticated central admin may manage any
 * other, matching this panel's existing "no RBAC layer on this side" model
 * (see CentralPanelProvider's docblock, TenantResource, StorageSettings).
 * The one guard NOT in the source but added here: an admin may not deactivate
 * or delete their own account, so master control can never lock itself out.
 */
class CentralAdminResource extends Resource
{
    protected static ?string $model = CentralAdmin::class;

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

    protected static ?string $navigationLabel = 'Admins';

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 3;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            TextInput::make('name')->required()->maxLength(255),
            TextInput::make('email')
                ->required()
                ->email()
                ->maxLength(255)
                ->rule(fn (?CentralAdmin $record) => Rule::unique('central_admins', 'email')->ignore($record?->id))
                ->dehydrateStateUsing(fn (string $state): string => mb_strtolower(trim($state))),
            TextInput::make('password')
                ->password()
                ->revealable()
                ->confirmed()
                ->rule(Password::min(12)->mixedCase()->numbers()->uncompromised())
                ->required(fn (string $operation): bool => $operation === 'create')
                ->dehydrated(fn (?string $state): bool => filled($state))
                ->helperText(fn (string $operation): string => $operation === 'create'
                    ? 'Hashed immediately, never stored in plain text.'
                    : 'Leave blank to keep the current password.'),
            TextInput::make('password_confirmation')
                ->password()
                ->revealable()
                ->required(fn (string $operation): bool => $operation === 'create')
                ->dehydrated(false),
            Toggle::make('is_active')
                ->label('Active')
                ->default(true)
                ->helperText('An inactive admin is blocked from signing in, without deleting the account.')
                // An admin cannot deactivate themselves — see class docblock.
                ->disabled(fn (?CentralAdmin $record): bool => $record !== null && Auth::guard('central')->id() === $record->id),
        ])->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')->searchable()->sortable(),
                TextColumn::make('email')->searchable()->sortable(),
                IconColumn::make('is_active')->boolean(),
                TextColumn::make('last_login_at')->dateTime()->placeholder('Never')->sortable(),
            ])
            ->defaultSort('name')
            ->recordActions([
                EditAction::make(),
                DeleteAction::make()
                    ->before(function (CentralAdmin $record, DeleteAction $action): void {
                        if (Auth::guard('central')->id() === $record->id) {
                            Notification::make()->title('You cannot delete your own account.')->danger()->send();
                            $action->cancel();
                        }
                    }),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListCentralAdmins::route('/'),
            'create' => CreateCentralAdmin::route('/create'),
            'edit' => EditCentralAdmin::route('/{record}/edit'),
        ];
    }
}
