<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ResellerRequestResource\Pages;
use App\Filament\Resources\ResellerRequestResource\RelationManagers;
use App\Models\ResellerRequest;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class ResellerRequestResource extends Resource
{
    protected static ?string $model = ResellerRequest::class;

    protected static ?string $navigationIcon = 'heroicon-o-clipboard-document-list';

    protected static ?string $navigationLabel = 'Solicitudes de Revendedor';

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

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Detalles de la Solicitud')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->label('Usuario')
                            ->relationship('user', 'name')
                            ->disabled()
                            ->required(),

                        Forms\Components\TextInput::make('phone')
                            ->label('Teléfono de Contacto')
                            ->disabled()
                            ->required(),

                        Forms\Components\Textarea::make('notes')
                            ->label('Notas / Experiencia')
                            ->disabled()
                            ->rows(4),

                        Forms\Components\Select::make('status')
                            ->label('Estado')
                            ->options([
                                'pending' => 'Pendiente',
                                'approved' => 'Aprobada',
                                'rejected' => 'Rechazada',
                            ])
                            ->required(),
                    ])
                    ->columns(2)
            ]);
    }

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

                Tables\Columns\TextColumn::make('user.email')
                    ->label('Correo Electrónico')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('phone')
                    ->label('Teléfono')
                    ->searchable(),

                Tables\Columns\TextColumn::make('status')
                    ->label('Estado')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'pending' => 'warning',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        default => 'secondary',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Fecha de Solicitud')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        'pending' => 'Pendiente',
                        'approved' => 'Aprobada',
                        'rejected' => 'Rechazada',
                    ]),
            ])
            ->actions([
                Tables\Actions\Action::make('approve')
                    ->label('Aprobar')
                    ->color('success')
                    ->icon('heroicon-o-check')
                    ->visible(fn (ResellerRequest $record): bool => $record->status === 'pending')
                    ->action(function (ResellerRequest $record) {
                        \DB::transaction(function () use ($record) {
                            $user = $record->user;
                            
                            // 1. Cambiar el rol del usuario a reseller
                            $resellerRole = \App\Models\Role::where('name', 'reseller')->first();
                            if ($resellerRole) {
                                $user->update(['role_id' => $resellerRole->id]);
                            }

                            // 2. Generar el código de revendedor único
                            $resellerCode = 'RES-' . \Str::upper(\Str::random(5));
                            while (\App\Models\ResellerProfile::where('reseller_code', $resellerCode)->exists()) {
                                $resellerCode = 'RES-' . \Str::upper(\Str::random(5));
                            }

                            // 3. Crear el perfil de revendedor
                            \App\Models\ResellerProfile::create([
                                'user_id' => $user->id,
                                'reseller_code' => $resellerCode,
                                'custom_link' => url('/r/' . $resellerCode),
                                'commission_preference' => 'cash',
                                'total_sales_count' => 0,
                                'total_commissions_earned' => 0.00,
                            ]);

                            // 4. Actualizar estado de la solicitud
                            $record->update(['status' => 'approved']);
                        });
                    })
                    ->requiresConfirmation(),

                Tables\Actions\Action::make('reject')
                    ->label('Rechazar')
                    ->color('danger')
                    ->icon('heroicon-o-x-mark')
                    ->visible(fn (ResellerRequest $record): bool => $record->status === 'pending')
                    ->action(function (ResellerRequest $record) {
                        $record->update(['status' => 'rejected']);
                    })
                    ->requiresConfirmation(),

                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\ListResellerRequests::route('/'),
            'create' => Pages\CreateResellerRequest::route('/create'),
            'edit' => Pages\EditResellerRequest::route('/{record}/edit'),
        ];
    }
}
