<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UpworkEarningResource\Pages;
use App\Models\UpworkEarning;
use Filament\Forms\Form;
use Filament\Resources\Pages\Page;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class UpworkEarningResource extends Resource
{
    protected static ?string $model = UpworkEarning::class;

    protected static ?string $navigationIcon   = 'heroicon-o-banknotes';
    protected static ?string $navigationGroup  = 'Comercial';
    protected static ?string $navigationLabel  = 'Transacciones Upwork';
    protected static ?string $modelLabel       = 'Transacción Upwork';
    protected static ?string $pluralModelLabel = 'Transacciones Upwork';
    protected static ?int    $navigationSort   = 9;

    // ── Clasificación de tipos ────────────────────────────────────────────────
    private const EARNING_TYPES  = ['Hourly', 'Fixed-price', 'Fixed Price', 'Bonus'];
    private const WITHDRAWAL_TYPES = ['Withdrawal', 'Withdrawal Fee'];
    private const EXPENSE_TYPES  = ['Connects', 'Subscription'];

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

    // ── Tabla ─────────────────────────────────────────────────────────────────
    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('transaction_date')
                    ->label('Fecha')
                    ->date('d/m/Y')
                    ->sortable(),

                Tables\Columns\TextColumn::make('payment_type')
                    ->label('Tipo')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'Hourly'         => 'success',
                        'Fixed-price',
                        'Fixed Price'    => 'info',
                        'Withdrawal'     => 'warning',
                        'Withdrawal Fee' => 'gray',
                        'Connects'       => 'danger',
                        'Subscription'   => 'danger',
                        default          => 'gray',
                    }),

                Tables\Columns\TextColumn::make('contract_title')
                    ->label('Descripción')
                    ->searchable()
                    ->limit(45)
                    ->tooltip(fn (UpworkEarning $r) => $r->contract_title),

                Tables\Columns\TextColumn::make('client_name')
                    ->label('Cliente')
                    ->placeholder('—')
                    ->searchable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('date_from')
                    ->label('Período')
                    ->formatStateUsing(function (UpworkEarning $record): string {
                        if (!$record->date_from || !$record->date_to) return '—';
                        if ($record->date_from->eq($record->date_to)) return '—';
                        return $record->date_from->format('d/m') . ' → ' . $record->date_to->format('d/m/Y');
                    })
                    ->toggleable(),

                Tables\Columns\TextColumn::make('amount')
                    ->label('Monto')
                    ->formatStateUsing(fn ($state) => '$' . number_format(abs((float) $state), 2))
                    ->sortable()
                    ->alignEnd()
                    ->color(fn (UpworkEarning $record): string =>
                        $record->amount >= 0 ? 'success' : 'danger'
                    ),

                Tables\Columns\TextColumn::make('account.name')
                    ->label('Cuenta')
                    ->placeholder('—')
                    ->badge()
                    ->color('warning')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('sale.title')
                    ->label('Venta vinculada')
                    ->placeholder('—')
                    ->limit(30)
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('transaction_date', 'desc')
            ->filters([
                Tables\Filters\Filter::make('periodo')
                    ->form([
                        \Filament\Forms\Components\DatePicker::make('desde')->label('Desde'),
                        \Filament\Forms\Components\DatePicker::make('hasta')->label('Hasta'),
                    ])
                    ->query(fn (Builder $q, array $data) => $q
                        ->when($data['desde'], fn ($q, $v) => $q->where('transaction_date', '>=', $v))
                        ->when($data['hasta'], fn ($q, $v) => $q->where('transaction_date', '<=', $v))
                    ),
            ])
            ->actions([])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->visible(fn () => auth()->user()?->isAdmin() ?? false),
                ]),
            ])
            ->striped()
            ->paginated([25, 50, 100]);
    }

    public static function form(Form $form): Form
    {
        return $form->schema([]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUpworkEarnings::route('/'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['client', 'sale', 'account', 'importedBy']);
    }
}
