<?php

namespace App\Filament\Widgets;

use App\Models\Subscription;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;

class LatestSubscriptionsWidget extends TableWidget
{
    protected static ?int $sort = 7;

    protected int | string | array $columnSpan = 'full';

    public function table(Table $table): Table
    {
        return $table
            ->query(
                Subscription::query()
                    ->with(['client', 'package', 'propertyTypes', 'facilities'])
                    ->latest('created_at')
            )
            ->heading('إدارة الاشتراكات')
            ->description('متابعة جميع الاشتراكات مع الفلاتر')
            ->columns([
                Tables\Columns\TextColumn::make('client.name')
                    ->label('العميل')
                    ->searchable()
                    ->sortable()
                    ->weight('bold')
                    ->icon('heroicon-m-user'),

                Tables\Columns\TextColumn::make('package.name')
                    ->label('الباقة')
                    ->formatStateUsing(fn ($record) => $record->package ? $record->package->getTranslation('name', 'ar') : '-')
                    ->badge()
                    ->color(fn (Subscription $record): string => match ($record->package?->color ?? '#f97316') {
                        '#f97316' => 'warning',
                        '#eab308' => 'warning',
                        '#a855f7' => 'success',
                        default => 'info',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('property_type_display')
                    ->label('نوع العقار')
                    ->state(fn (Subscription $record) => $record->propertyTypes->count() > 0
                        ? $record->propertyTypes->map(fn ($pt) => $pt->getTranslation('name', 'ar'))->implode(', ')
                        : '-'
                    )
                    ->badge()
                    ->color('primary')
                    ->icon('heroicon-m-home-modern'),

                Tables\Columns\TextColumn::make('start_date')
                    ->label('البداية')
                    ->date('Y-m-d')
                    ->sortable(),

                Tables\Columns\TextColumn::make('end_date')
                    ->label('الانتهاء')
                    ->date('Y-m-d')
                    ->sortable()
                    ->color(fn (Subscription $record): string => $this->getEndDateColor($record)),

                Tables\Columns\TextColumn::make('remaining_days')
                    ->label('الأيام المتبقية')
                    ->state(function (Subscription $record): string {
                        if ($record->status !== 'active') {
                            return '-';
                        }
                        $days = now()->startOfDay()->diffInDays($record->end_date, false);
                        if ($days < 0) {
                            return 'منتهي';
                        }
                        return $days . ' يوم';
                    })
                    ->badge()
                    ->color(function (Subscription $record): string {
                        if ($record->status !== 'active') {
                            return 'gray';
                        }
                        $days = now()->startOfDay()->diffInDays($record->end_date, false);
                        if ($days < 0) {
                            return 'danger';
                        }
                        if ($days <= 7) {
                            return 'danger';
                        }
                        if ($days <= 30) {
                            return 'warning';
                        }
                        return 'success';
                    }),

                Tables\Columns\TextColumn::make('status')
                    ->label('الحالة')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'active' => 'نشط',
                        'expired' => 'منتهي',
                        'cancelled' => 'ملغي',
                        'suspended' => 'معلق',
                        default => $state,
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'active' => 'success',
                        'expired' => 'danger',
                        'cancelled' => 'gray',
                        'suspended' => 'warning',
                        default => 'gray',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('amount_paid')
                    ->label('المبلغ')
                    ->money('SAR')
                    ->sortable(),

                Tables\Columns\TextColumn::make('payment_status')
                    ->label('حالة الدفع')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'paid' => 'مدفوع',
                        'pending' => 'معلق',
                        'refunded' => 'مسترد',
                        default => $state,
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'paid' => 'success',
                        'pending' => 'warning',
                        'refunded' => 'danger',
                        default => 'gray',
                    }),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('حالة الاشتراك')
                    ->options([
                        'active' => '✅ نشط',
                        'expired' => '❌ منتهي',
                        'cancelled' => '🚫 ملغي',
                        'suspended' => '⏸️ معلق',
                    ])
                    ->placeholder('كل الحالات'),

                Tables\Filters\Filter::make('expiring_soon')
                    ->label('⚠️ تنتهي خلال 7 أيام')
                    ->query(fn ($query) => $query
                        ->where('status', 'active')
                        ->where('end_date', '>=', now()->toDateString())
                        ->where('end_date', '<=', now()->addDays(7)->toDateString())
                    ),

                Tables\Filters\Filter::make('expiring_month')
                    ->label('📅 تنتهي خلال 30 يوم')
                    ->query(fn ($query) => $query
                        ->where('status', 'active')
                        ->where('end_date', '>=', now()->toDateString())
                        ->where('end_date', '<=', now()->addDays(30)->toDateString())
                    ),

                Tables\Filters\Filter::make('already_expired')
                    ->label('🔴 منتهية فعلاً')
                    ->query(fn ($query) => $query
                        ->where(function ($q) {
                            $q->where('status', 'expired')
                                ->orWhere(function ($q2) {
                                    $q2->where('status', 'active')
                                        ->where('end_date', '<', now()->toDateString());
                                });
                        })
                    ),

                Tables\Filters\SelectFilter::make('package_id')
                    ->label('الباقة')
                    ->relationship('package', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => $record->getTranslation('name', 'ar') . ' / ' . $record->getTranslation('name', 'en'))
                    ->searchable()
                    ->preload(),

                Tables\Filters\SelectFilter::make('payment_status')
                    ->label('حالة الدفع')
                    ->options([
                        'paid' => '✅ مدفوع',
                        'pending' => '⏳ معلق',
                        'refunded' => '↩️ مسترد',
                    ])
                    ->placeholder('كل حالات الدفع'),
            ])
            ->actions([
                \Filament\Actions\Action::make('view')
                    ->label('عرض')
                    ->icon('heroicon-o-eye')
                    ->url(fn (Subscription $record): string => route('filament.admin.resources.subscriptions.edit', $record))
                    ->openUrlInNewTab(false),
            ])
            ->defaultSort('end_date', 'asc')
            ->paginated([5, 10, 25])
            ->defaultPaginationPageOption(5)
            ->poll('30s');
    }

    private function getEndDateColor(Subscription $record): string
    {
        if ($record->status === 'expired' || ($record->end_date < now()->toDateString() && $record->status === 'active')) {
            return 'danger';
        }

        if ($record->status === 'active' && $record->end_date <= now()->addDays(7)->toDateString()) {
            return 'danger';
        }

        if ($record->status === 'active' && $record->end_date <= now()->addDays(30)->toDateString()) {
            return 'warning';
        }

        return 'success';
    }
}
