<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TenantResource\Pages;
use App\Filament\Resources\TenantResource\RelationManagers\PackagePurchasesRelationManager;
use App\Filament\Resources\TenantResource\RelationManagers\TenantPackagesRelationManager;
use App\Models\Tenant;
use BackedEnum;
use Filament\Actions;
use Filament\Forms;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Route;
use UnitEnum;

class TenantResource extends Resource
{
    protected static ?string $model = Tenant::class;

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-building-office';

    protected static UnitEnum|string|null $navigationGroup = null;

    public static function getNavigationGroup(): UnitEnum|string|null
    {
        return __('admin.nav.platform_management');
    }

    protected static ?int $navigationSort = 10;

    public static function form(Schema $form): Schema
    {

        return $form->schema([
            TextInput::make('user.full_name')
                ->label(__('admin.tenants.fields.name'))
                ->required()
                ->readOnly()
                ->dehydrated(false)
                ->default(fn (Tenant $record) => $record->user?->full_name ?? 'Unbekannt'),
            TextInput::make('slug')
                ->label(__('admin.tenants.fields.slug'))
                ->required()
                ->unique(ignoreRecord: true)
                ->maxLength(255),
            TextInput::make('contact_email')
                ->label(__('admin.tenants.fields.contact_email'))
                ->email()
                ->required()
                ->maxLength(255),
            TextInput::make('paddle_customer_id')
                ->label('Paddle Customer ID')
                ->maxLength(191)
                ->helperText('Verknuepfung mit Paddle Billing Kundenkonto.')
                ->nullable(),
            TextInput::make('total_revenue')
                ->label(__('admin.tenants.fields.total_revenue'))
                ->prefix('€')
                ->numeric()
                ->step(0.01)
                ->readOnly(),
            Select::make('active_reseller_package_id')
                ->label(__('admin.tenants.fields.active_reseller_package'))
                ->relationship('activeResellerPackage.package', 'name')
                ->searchable()
                ->preload()
                ->nullable(),
            TextInput::make('remaining_events')
                ->label(__('admin.tenants.fields.remaining_events'))
                ->readOnly()
                ->dehydrated(false)
                ->default(fn (Tenant $record) => $record->activeResellerPackage?->remaining_events ?? 0),
            Toggle::make('is_active')
                ->label(__('admin.tenants.fields.is_active'))
                ->default(true),
            Toggle::make('is_suspended')
                ->label(__('admin.tenants.fields.is_suspended'))
                ->default(false),
            KeyValue::make('features')
                ->label(__('admin.tenants.fields.features'))
                ->keyLabel(__('admin.common.key'))
                ->valueLabel(__('admin.common.value')),
        ])->columns(2);
    }

    public static function table(Table $table): Table
    {

        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')->sortable(),
                Tables\Columns\TextColumn::make('user.full_name')
                    ->label(__('admin.tenants.fields.name'))
                    ->searchable()
                    ->sortable()
                    ->getStateUsing(fn (Tenant $record) => $record->user?->full_name ?? 'Unbekannt'),
                Tables\Columns\TextColumn::make('slug')->searchable(),
                Tables\Columns\TextColumn::make('contact_email'),
                Tables\Columns\TextColumn::make('paddle_customer_id')
                    ->label('Paddle Customer')
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->formatStateUsing(fn ($state) => $state ?: '-'),
                Tables\Columns\TextColumn::make('active_reseller_package_id')
                    ->label(__('admin.tenants.fields.active_package'))
                    ->badge()
                    ->color('success')
                    ->getStateUsing(fn (Tenant $record) => $record->activeResellerPackage?->name ?? 'Kein aktives Package'),
                Tables\Columns\TextColumn::make('active_reseller_package_id')
                    ->label(__('admin.tenants.fields.remaining_events'))
                    ->badge()
                    ->color(fn ($state) => $state < 1 ? 'danger' : 'success')
                    ->getStateUsing(fn (Tenant $record) => $record->activeResellerPackage?->remaining_events ?? 0),
                Tables\Columns\TextColumn::make('active_reseller_package_id')
                    ->dateTime()
                    ->label(__('admin.tenants.fields.package_expires_at'))
                    ->badge()
                    ->color(fn ($state) => $state && $state->isPast() ? 'danger' : 'success')
                    ->getStateUsing(fn (Tenant $record) => $record->activeResellerPackage?->expires_at),
                Tables\Columns\TextColumn::make('total_revenue')
                    ->money('EUR')
                    ->sortable(),
                Tables\Columns\IconColumn::make('is_active')
                    ->boolean()
                    ->color(fn (bool $state): string => $state ? 'success' : 'danger'),
                Tables\Columns\TextColumn::make('last_activity_at')->since()->label(__('admin.common.last_activity')),
                Tables\Columns\TextColumn::make('created_at')->dateTime()->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([])
            ->actions([
                Actions\EditAction::make(),
                Actions\Action::make('add_package')
                    ->label('Package hinzufügen')
                    ->icon('heroicon-o-plus')
                    ->form([
                        Select::make('package_id')
                            ->label('Package')
                            ->options(\App\Models\Package::where('type', 'reseller')->pluck('name', 'id'))
                            ->searchable()
                            ->preload()
                            ->required(),
                        Forms\Components\DateTimePicker::make('expires_at')
                            ->label('Ablaufdatum')
                            ->default(now()->addYear()),
                        Forms\Components\Textarea::make('reason')->label('Grund')->rows(3),
                    ])
                    ->action(function (Tenant $record, array $data) {
                        \App\Models\TenantPackage::create([
                            'tenant_id' => $record->id,
                            'package_id' => $data['package_id'],
                            'expires_at' => $data['expires_at'],
                            'active' => true,
                            'reason' => $data['reason'] ?? null,
                        ]);
                        \App\Models\PackagePurchase::create([
                            'tenant_id' => $record->id,
                            'package_id' => $data['package_id'],
                            'provider' => 'manual',
                            'provider_id' => 'manual',
                            'type' => 'reseller_subscription',
                            'price' => 0,
                            'metadata' => ['reason' => $data['reason'] ?? 'manual assignment'],
                        ]);
                    }),
                Actions\Action::make('suspend')
                    ->label('Suspendieren')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->authorize(fn (Tenant $record): bool => auth()->user()?->can('suspend', $record) ?? false)
                    ->action(fn (Tenant $record) => $record->update(['is_suspended' => true])),
                Actions\Action::make('export')
                    ->label('Daten exportieren')
                    ->icon('heroicon-o-arrow-down-tray')
                    ->url(fn (Tenant $record) => Route::has('admin.tenants.export') ? route('admin.tenants.export', $record) : null)
                    ->visible(fn () => Route::has('admin.tenants.export'))
                    ->openUrlInNewTab(),
            ])
            ->bulkActions([
                Actions\DeleteBulkAction::make(),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTenants::route('/'),
            'view' => Pages\ViewTenant::route('/{record}'),
            'edit' => Pages\EditTenant::route('/{record}/edit'),
        ];
    }

    public static function getRelations(): array
    {

        return [
            TenantPackagesRelationManager::class,
            PackagePurchasesRelationManager::class,
        ];
    }
}
