<?php

namespace App\Filament\Resources\Subscriptions\Tables;

use App\Models\Subscription;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;

class SubscriptionsTable
{
    /** @var array<string, string> */
    private const BILLING_LABELS = [
        Subscription::BILLING_MONTHLY => 'Mensual',
        Subscription::BILLING_QUARTERLY => 'Trimestral',
        Subscription::BILLING_SEMIANNUAL => 'Semestral',
        Subscription::BILLING_ANNUAL => 'Anual',
    ];

    /** @var array<string, string> */
    private const STATUS_LABELS = [
        Subscription::STATUS_TRIAL => 'Prueba',
        Subscription::STATUS_ACTIVE => 'Activa',
        Subscription::STATUS_GRACE => 'Gracia',
        Subscription::STATUS_EXPIRED => 'Expirada',
        Subscription::STATUS_CANCELED => 'Cancelada',
        Subscription::STATUS_SUSPENDED => 'Suspendida',
    ];

    /** @var array<string, string> */
    private const STATUS_COLORS = [
        Subscription::STATUS_TRIAL => 'info',
        Subscription::STATUS_ACTIVE => 'success',
        Subscription::STATUS_GRACE => 'warning',
        Subscription::STATUS_EXPIRED => 'danger',
        Subscription::STATUS_CANCELED => 'gray',
        Subscription::STATUS_SUSPENDED => 'danger',
    ];

    public static function configure(Table $table): Table
    {
        $isSuperAdmin = Auth::user()?->isSuperAdmin() ?? false;

        return $table
            ->columns([
                // Compañía (solo Super Admin, que ve todas las empresas)
                TextColumn::make('company.name')
                    ->label('Compañía')
                    ->searchable()
                    ->sortable()
                    ->hidden(fn () => ! $isSuperAdmin),

                // Plan: el NOMBRE del plan (antes apuntaba a la relación → salía el JSON).
                TextColumn::make('plan.name')
                    ->label('Plan')
                    ->badge()
                    ->color('primary')
                    ->placeholder('Sin plan')
                    ->sortable(),

                // Ciclo de facturación (columna real billing_cycle).
                TextColumn::make('billing_cycle')
                    ->label('Facturación')
                    ->badge()
                    ->color('gray')
                    ->formatStateUsing(fn (?string $state): string => self::BILLING_LABELS[$state] ?? (string) $state),

                // Estado real (controla el acceso). Antes se mostraba is_active, inerte.
                TextColumn::make('status')
                    ->label('Estado')
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => self::STATUS_LABELS[$state] ?? (string) $state)
                    ->color(fn (?string $state): string => self::STATUS_COLORS[$state] ?? 'gray')
                    ->sortable(),

                TextColumn::make('starts_at')
                    ->label('Inicio')
                    ->date('d/m/Y')
                    ->sortable(),

                TextColumn::make('ends_at')
                    ->label('Fin')
                    ->date('d/m/Y')
                    ->sortable()
                    ->color(fn ($state): string => $state && now()->greaterThan($state) ? 'danger' : 'success'),

                TextColumn::make('created_at')
                    ->label('Creado')
                    ->dateTime('d/m/Y H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('created_at', 'desc')
            ->filters([
                SelectFilter::make('status')
                    ->label('Estado')
                    ->options(self::STATUS_LABELS),
            ])
            ->recordActions([
                EditAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }
}
