<?php

namespace App\Filament\Resources;

use App\Enums\ClientOrigin;
use App\Enums\Currency;
use App\Filament\Resources\ClientResource\Pages;
use App\Models\Client;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class ClientResource extends Resource
{
    protected static ?string $model = Client::class;
    protected static ?string $navigationIcon  = 'heroicon-o-users';
    protected static ?string $navigationGroup = 'Comercial';
    protected static ?string $navigationLabel = 'Clientes';
    protected static ?string $modelLabel      = 'Cliente';
    protected static ?string $pluralModelLabel = 'Clientes';
    protected static ?int    $navigationSort  = 1;

    // ── Permisos ──────────────────────────────────────────────────────────────
    public static function canViewAny(): bool { return true; }
    public static function canCreate(): bool  { return true; }
    public static function canEdit($record): bool { return true; }
    public static function canDelete($record): bool
    {
        return auth()->user()?->isAdmin() || auth()->user()?->isContador();
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make('Información del cliente')->schema([
                Forms\Components\TextInput::make('name')
                    ->label('Nombre')
                    ->required()
                    ->maxLength(255)
                    ->columnSpan(2),

                Forms\Components\Select::make('origin')
                    ->label('Origen')
                    ->options(collect(ClientOrigin::cases())->mapWithKeys(
                        fn ($e) => [$e->value => $e->label()]
                    ))
                    ->required()
                    ->default(ClientOrigin::ManualInternacional->value),

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

                Forms\Components\TextInput::make('country')
                    ->label('País')
                    ->maxLength(100),

                Forms\Components\TextInput::make('hourly_rate')
                    ->label('Tarifa por hora (USD)')
                    ->numeric()
                    ->prefix('$')
                    ->step(0.01),
            ])->columns(2),

            Forms\Components\Section::make('Contacto')->schema([
                Forms\Components\TextInput::make('contact_name')
                    ->label('Nombre de contacto')
                    ->maxLength(255),

                Forms\Components\TextInput::make('contact_email')
                    ->label('Email')
                    ->email()
                    ->maxLength(255),

                Forms\Components\TextInput::make('contact_phone')
                    ->label('Teléfono')
                    ->tel()
                    ->maxLength(50),

                Forms\Components\Textarea::make('notes')
                    ->label('Notas')
                    ->rows(3)
                    ->columnSpanFull(),
            ])->columns(3),
        ]);
    }

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

                Tables\Columns\BadgeColumn::make('origin')
                    ->label('Origen')
                    ->formatStateUsing(fn ($state) => $state instanceof ClientOrigin ? $state->label() : $state)
                    ->colors([
                        'primary'  => 'upwork',
                        'success'  => 'bolivia',
                        'warning'  => 'renovacion',
                        'gray'     => 'manual_internacional',
                    ]),

                Tables\Columns\TextColumn::make('country')
                    ->label('País')
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('contact_email')
                    ->label('Email')
                    ->copyable(),

                Tables\Columns\TextColumn::make('sales_count')
                    ->label('Ventas')
                    ->counts('sales')
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Creado')
                    ->date('d/m/Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('origin')
                    ->label('Origen')
                    ->options(collect(ClientOrigin::cases())->mapWithKeys(
                        fn ($e) => [$e->value => $e->label()]
                    )),

                Tables\Filters\SelectFilter::make('currency_default')
                    ->label('Moneda')
                    ->options(collect(Currency::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(),
                ]),
            ])
            ->defaultSort('name');
    }

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

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