<?php

namespace App\Filament\Resources;

use App\Enums\Currency;
use App\Filament\Resources\SystemSettingResource\Pages;
use App\Models\SystemSetting;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class SystemSettingResource extends Resource
{
    protected static ?string $model = SystemSetting::class;
    protected static ?string $navigationIcon   = 'heroicon-o-cog-6-tooth';
    protected static ?string $navigationGroup  = 'Configuración';
    protected static ?string $navigationLabel  = 'Configuración global';
    protected static ?string $modelLabel       = 'Configuración';
    protected static ?string $pluralModelLabel = 'Configuración global';
    protected static ?int    $navigationSort   = 2;

    // ── Permisos: solo admin_sistema ──────────────────────────────────────────
    public static function canViewAny(): bool { return auth()->user()?->isAdmin() ?? false; }
    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 false; } // configuración nunca se borra

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make('Moneda y tipo de cambio')->schema([
                Forms\Components\Select::make('base_currency')
                    ->label('Moneda base')
                    ->options(collect(Currency::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()]))
                    ->required()
                    ->default(Currency::USD->value),

                Forms\Components\TextInput::make('exchange_rate_usd_bob')
                    ->label('Tipo de cambio USD → BOB')
                    ->numeric()
                    ->step(0.0001)
                    ->required()
                    ->suffix('BOB por 1 USD')
                    ->helperText('Ejemplo: 6.96 significa 1 USD = 6.96 BOB'),
            ])->columns(2),

            Forms\Components\Section::make('Comisiones')->schema([
                Forms\Components\TextInput::make('account_commission_pct')
                    ->label('Comisión Account Manager (%)')
                    ->numeric()
                    ->step(0.01)
                    ->suffix('%')
                    ->required()
                    ->default(5.00)
                    ->helperText('Porcentaje fijo aplicado sobre proyectos cobrados. Por defecto: 5%.'),

                Forms\Components\TextInput::make('sales_commission_pct')
                    ->label('Comisión Vendedor (%) — por defecto')
                    ->numeric()
                    ->step(0.01)
                    ->suffix('%')
                    ->required()
                    ->default(25.00)
                    ->helperText('Se puede sobreescribir por venta individual. Por defecto: 25%.'),
            ])->columns(2),

            Forms\Components\Section::make('🤖 Asistente IA — Nuna Chat')
                ->description('Configuración para el asistente de voz/chat integrado con Claude.')
                ->schema([
                    Forms\Components\TextInput::make('claude_api_key')
                        ->label('API Key de Claude (Anthropic)')
                        ->password()
                        ->revealable()
                        ->placeholder('sk-ant-...')
                        ->helperText('Obtené tu API key en console.anthropic.com')
                        ->columnSpanFull(),

                    Forms\Components\Select::make('claude_model')
                        ->label('Modelo de Claude')
                        ->options([
                            'claude-haiku-4-5-20251001' => 'Claude Haiku 4.5 (rápido, económico — recomendado)',
                            'claude-sonnet-4-6'         => 'Claude Sonnet 4.6 (más preciso)',
                        ])
                        ->default('claude-haiku-4-5-20251001')
                        ->required(),
                ])->columns(2),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('base_currency')
                    ->label('Moneda base')
                    ->formatStateUsing(fn ($state) => $state instanceof Currency ? $state->value : $state),

                Tables\Columns\TextColumn::make('exchange_rate_usd_bob')
                    ->label('Tipo de cambio USD→BOB')
                    ->suffix(' BOB'),

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Última actualización')
                    ->dateTime('d/m/Y H:i'),
            ])
            ->actions([
                Tables\Actions\EditAction::make()->label('Editar'),
            ])
            ->paginated(false);
    }

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

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