<?php

namespace App\Filament\Resources;

use App\Enums\AccountFeeType;
use App\Enums\Currency;
use App\Filament\Resources\AccountResource\Pages;
use App\Models\Account;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class AccountResource extends Resource
{
    protected static ?string $model = Account::class;
    protected static ?string $navigationIcon   = 'heroicon-o-building-library';
    protected static ?string $navigationGroup  = 'Configuración';
    protected static ?string $navigationLabel  = 'Cuentas destino';
    protected static ?string $modelLabel       = 'Cuenta';
    protected static ?string $pluralModelLabel = 'Cuentas destino';
    protected static ?int    $navigationSort   = 1;

    // ── Permisos: contador puede ver, solo admin puede modificar ──────────────
    public static function canViewAny(): bool
    {
        return auth()->user()?->isAdmin() || auth()->user()?->isContador();
    }
    public static function canCreate(): bool  { return auth()->user()?->isAdmin() ?? false; }
    public static function canEdit($record): bool { return auth()->user()?->isAdmin() ?? false; }
    public static function canDelete($record): bool { return auth()->user()?->isAdmin() ?? false; }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make()->schema([
                Forms\Components\TextInput::make('name')
                    ->label('Nombre de la cuenta')
                    ->required()
                    ->maxLength(255),

                Forms\Components\Select::make('currency')
                    ->label('Moneda')
                    ->options(collect(Currency::cases())->mapWithKeys(
                        fn ($e) => [$e->value => $e->label()]
                    ))
                    ->required()
                    ->default(Currency::USD->value),

                Forms\Components\Select::make('fee_type')
                    ->label('Tipo de comisión')
                    ->options(collect(AccountFeeType::cases())->mapWithKeys(
                        fn ($e) => [$e->value => $e->label()]
                    ))
                    ->required()
                    ->default(AccountFeeType::None->value)
                    ->live(),

                Forms\Components\TextInput::make('fee_percent')
                    ->label('Comisión (%)')
                    ->numeric()
                    ->suffix('%')
                    ->step(0.01)
                    ->default(0)
                    ->visible(fn (Get $get) => $get('fee_type') === AccountFeeType::Takenos->value),

                Forms\Components\TextInput::make('fee_fixed')
                    ->label('Comisión fija ($)')
                    ->numeric()
                    ->prefix('$')
                    ->step(0.01)
                    ->default(0)
                    ->visible(fn (Get $get) => $get('fee_type') === AccountFeeType::Takenos->value),
            ])->columns(2),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Nombre')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\BadgeColumn::make('currency')
                    ->label('Moneda')
                    ->formatStateUsing(fn ($state) => $state instanceof Currency ? $state->value : $state)
                    ->colors(['success' => 'USD', 'warning' => 'BOB']),

                Tables\Columns\BadgeColumn::make('fee_type')
                    ->label('Comisión')
                    ->formatStateUsing(fn ($state) => $state instanceof AccountFeeType ? $state->label() : $state)
                    ->colors(['gray' => 'none', 'warning' => 'takenos']),

                Tables\Columns\TextColumn::make('fee_percent')
                    ->label('%')
                    ->suffix('%')
                    ->sortable(),

                Tables\Columns\TextColumn::make('fee_fixed')
                    ->label('Fijo')
                    ->prefix('$')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('currency')
                    ->label('Moneda')
                    ->options(collect(Currency::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()])),

                Tables\Filters\SelectFilter::make('fee_type')
                    ->label('Tipo comisión')
                    ->options(collect(AccountFeeType::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()])),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [];
    }

    public static function getPages(): array
    {
        return [
            'index'  => Pages\ListAccounts::route('/'),
            'create' => Pages\CreateAccount::route('/create'),
            'edit'   => Pages\EditAccount::route('/{record}/edit'),
        ];
    }
}
