<?php

namespace App\Filament\Resources;

use App\Enums\Currency;
use App\Enums\RenewalStatus;
use App\Filament\Resources\RenewalResource\Pages;
use App\Models\Renewal;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class RenewalResource extends Resource
{
    protected static ?string $model = Renewal::class;
    protected static ?string $navigationIcon   = 'heroicon-o-arrow-path';
    protected static ?string $navigationGroup  = 'Comercial';
    protected static ?string $navigationLabel  = 'Renovaciones';
    protected static ?string $modelLabel       = 'Renovación';
    protected static ?string $pluralModelLabel = 'Renovaciones';
    protected static ?int    $navigationSort   = 3;

    // ── 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('Datos principales')->schema([
                Forms\Components\Select::make('client_id')
                    ->label('Cliente')
                    ->relationship('client', 'name')
                    ->searchable()
                    ->preload()
                    ->required(),

                Forms\Components\Select::make('status')
                    ->label('Estado')
                    ->options(collect(RenewalStatus::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()]))
                    ->required()
                    ->default(RenewalStatus::Active->value)
                    ->live(),

                Forms\Components\DatePicker::make('contract_start_date')
                    ->label('Inicio de contrato'),

                Forms\Components\DatePicker::make('next_due_date')
                    ->label('Próximo vencimiento')
                    ->required(),

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

            Forms\Components\Section::make('Servicios')->schema([
                Forms\Components\Toggle::make('domain_enabled')
                    ->label('Dominio')
                    ->live(),

                Forms\Components\TextInput::make('domain_amount')
                    ->label('Costo dominio')
                    ->numeric()
                    ->prefix('$')
                    ->step(0.01)
                    ->visible(fn (Get $get) => (bool) $get('domain_enabled')),

                Forms\Components\Toggle::make('hosting_enabled')
                    ->label('Hosting')
                    ->live(),

                Forms\Components\TextInput::make('hosting_amount')
                    ->label('Costo hosting')
                    ->numeric()
                    ->prefix('$')
                    ->step(0.01)
                    ->visible(fn (Get $get) => (bool) $get('hosting_enabled')),
            ])->columns(2),

            Forms\Components\Section::make('Pago')
                ->schema([
                    Forms\Components\DatePicker::make('paid_date')
                        ->label('Fecha de pago'),

                    Forms\Components\Textarea::make('paid_note')
                        ->label('Nota de pago')
                        ->rows(2)
                        ->columnSpanFull(),
                ])
                ->columns(2)
                ->visible(fn (Get $get) => $get('status') === RenewalStatus::Paid->value),
        ]);
    }

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

                Tables\Columns\TextColumn::make('next_due_date')
                    ->label('Vence')
                    ->date('d/m/Y')
                    ->sortable()
                    ->color(fn (Renewal $record) => match(true) {
                        $record->next_due_date->isPast() => 'danger',
                        $record->next_due_date->diffInDays(now()) <= 30 => 'warning',
                        default => null,
                    }),

                Tables\Columns\BadgeColumn::make('status')
                    ->label('Estado')
                    ->formatStateUsing(fn ($state) => $state instanceof RenewalStatus ? $state->label() : $state)
                    ->colors([
                        'warning' => 'pending',
                        'info'    => 'active',
                        'success' => 'paid',
                        'danger'  => 'cancelled',
                    ]),

                Tables\Columns\IconColumn::make('domain_enabled')
                    ->label('Dom.')
                    ->boolean(),

                Tables\Columns\IconColumn::make('hosting_enabled')
                    ->label('Host.')
                    ->boolean(),

                Tables\Columns\TextColumn::make('total_amount')
                    ->label('Total')
                    ->getStateUsing(fn (Renewal $record): float => $record->total_amount)
                    ->numeric(decimalPlaces: 2)
                    ->prefix('$'),

                Tables\Columns\BadgeColumn::make('currency')
                    ->label('Mon.')
                    ->formatStateUsing(fn ($state) => $state instanceof Currency ? $state->value : $state)
                    ->colors(['success' => 'USD', 'warning' => 'BOB']),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('Estado')
                    ->options(collect(RenewalStatus::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()])),

                Tables\Filters\SelectFilter::make('client_id')
                    ->label('Cliente')
                    ->relationship('client', 'name')
                    ->searchable()
                    ->preload(),

                Tables\Filters\Filter::make('due_soon')
                    ->label('Vence en 30 días')
                    ->query(fn (Builder $q) => $q->whereDate('next_due_date', '<=', now()->addDays(30))
                        ->where('status', '!=', RenewalStatus::Paid->value)),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->defaultSort('next_due_date');
    }

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

    public static function getPages(): array
    {
        return [
            'index'  => Pages\ListRenewals::route('/'),
            'create' => Pages\CreateRenewal::route('/create'),
            'view'   => Pages\ViewRenewal::route('/{record}'),
            'edit'   => Pages\EditRenewal::route('/{record}/edit'),
        ];
    }
}
