<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ResellerProfileResource\Pages;
use App\Models\ResellerProfile;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class ResellerProfileResource extends Resource
{
    protected static ?string $model = ResellerProfile::class;

    protected static ?string $navigationIcon = 'heroicon-o-identification';

    protected static ?string $navigationLabel = 'Revendedores';

    protected static ?string $modelLabel = 'Perfil de Revendedor';

    protected static ?string $pluralModelLabel = 'Perfiles de Revendedor';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Vinculación y Códigos')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->label('Usuario Asociado')
                            ->relationship('user', 'name', fn ($query) => $query->where('role', 'reseller'))
                            ->searchable()
                            ->required()
                            ->unique(ignoreRecord: true),

                        Forms\Components\TextInput::make('reseller_code')
                            ->label('Código Único de Revendedor')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->maxLength(100),

                        Forms\Components\TextInput::make('custom_link')
                            ->label('Enlace de Referido')
                            ->url()
                            ->required()
                            ->maxLength(255),

                        Forms\Components\FileUpload::make('qr_code_path')
                            ->label('Código QR Personalizado')
                            ->disk('public')
                            ->directory('resellers/qrs')
                            ->image(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Comisiones y Rendimiento')
                    ->schema([
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Select::make('commission_preference')
                                    ->label('Preferencia de Comisión')
                                    ->options([
                                        'cash' => 'Efectivo (10%)',
                                        'credit' => 'Crédito Sorteos (15%)',
                                    ])
                                    ->required()
                                    ->default('cash'),

                                Forms\Components\TextInput::make('total_sales_count')
                                    ->label('Total Ventas Realizadas')
                                    ->numeric()
                                    ->disabled()
                                    ->default(0),

                                Forms\Components\TextInput::make('total_commissions_earned')
                                    ->label('Total Comisiones Ganadas')
                                    ->numeric()
                                    ->prefix('₡')
                                    ->disabled()
                                    ->default(0.00),
                            ]),
                    ]),
            ]);
    }

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

                Tables\Columns\TextColumn::make('reseller_code')
                    ->label('Código')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('commission_preference')
                    ->label('Preferencia')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'cash' => 'success',
                        'credit' => 'warning',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'cash' => 'Efectivo (10%)',
                        'credit' => 'Crédito (15%)',
                    }),

                Tables\Columns\TextColumn::make('total_sales_count')
                    ->label('Total Ventas')
                    ->numeric()
                    ->sortable(),

                Tables\Columns\TextColumn::make('total_commissions_earned')
                    ->label('Comisiones Totales')
                    ->numeric(decimalPlaces: 2)
                    ->prefix('₡')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('commission_preference')
                    ->label('Preferencia de Pago')
                    ->options([
                        'cash' => 'Efectivo',
                        'credit' => 'Crédito',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

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