<?php

namespace App\Filament\Resources;

use App\Exports\SubscriptionsExport;
use App\Filament\Resources\SubscriptionResource\Pages;
use App\Models\AdditionalFacility;
use App\Models\PropertyType;
use App\Models\Subscription;
use Barryvdh\DomPDF\Facade\Pdf;
use Filament\Actions\BulkAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Maatwebsite\Excel\Facades\Excel;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Carbon;

class SubscriptionResource extends Resource
{
    protected static ?string $model = Subscription::class;

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-credit-card';

    protected static ?string $navigationLabel = 'الاشتراكات';

    protected static ?string $modelLabel = 'اشتراك';

    protected static ?string $pluralModelLabel = 'الاشتراكات';

    protected static string | \UnitEnum | null $navigationGroup = 'إدارة الاشتراكات';

    protected static ?int $navigationSort = 2;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('معلومات الاشتراك')
                    ->description('اختر العميل والباقة')
                    ->components([
                        Select::make('client_id')
                            ->label('العميل')
                            ->relationship('client', 'name')
                            ->required()
                            ->searchable()
                            ->preload()
                            ->createOptionForm([
                                \Filament\Forms\Components\TextInput::make('name')
                                    ->label('الاسم')
                                    ->required(),
                                \Filament\Forms\Components\TextInput::make('email')
                                    ->label('البريد الإلكتروني')
                                    ->email()
                                    ->required(),
                                \Filament\Forms\Components\TextInput::make('phone')
                                    ->label('رقم الهاتف')
                                    ->tel(),
                            ]),
                        Select::make('package_id')
                            ->label('الباقة')
                            ->relationship('package', 'name')
                            ->getOptionLabelFromRecordUsing(fn ($record) => $record->getTranslation('name', 'ar') . ' / ' . $record->getTranslation('name', 'en'))
                            ->required()
                            ->searchable()
                            ->preload()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, $get) {
                                if ($state) {
                                    $package = \App\Models\Package::find($state);
                                    if ($package) {
                                        $startDate = $get('start_date') ?: now()->toDateString();
                                        $endDate = Carbon::parse($startDate)->addDays($package->duration_days)->toDateString();
                                        $set('end_date', $endDate);
                                        $set('amount_paid', $package->price);
                                    }
                                }
                            }),
                    ])->columns(2),

                Section::make('نوع العقار')
                    ->description('اختر نوع العقار وعدد الوحدات')
                    ->icon('heroicon-o-home-modern')
                    ->components([
                        Repeater::make('subscription_properties')
                            ->label('')
                            ->schema([
                                Select::make('property_type_id')
                                    ->label('نوع العقار')
                                    ->options(
                                        PropertyType::where('is_active', true)
                                            ->orderBy('sort_order')
                                            ->get()
                                            ->mapWithKeys(fn ($pt) => [$pt->id => $pt->getTranslation('name', 'ar') . ' / ' . $pt->getTranslation('name', 'en')])
                                    )
                                    ->required()
                                    ->searchable(),
                                TextInput::make('quantity')
                                    ->label('العدد')
                                    ->numeric()
                                    ->default(1)
                                    ->minValue(0)
                                    ->required(),
                            ])
                            ->columns(2)
                            ->addActionLabel('إضافة نوع عقار')
                            ->defaultItems(0)
                            ->reorderable(false)
                            ->columnSpanFull(),
                    ]),

                Section::make('المرافق الإضافية')
                    ->description('اختر المرافق الإضافية مع الكمية والسعر')
                    ->icon('heroicon-o-building-office-2')
                    ->components([
                        Repeater::make('subscription_facilities')
                            ->label('')
                            ->schema([
                                Select::make('additional_facility_id')
                                    ->label('المرفق')
                                    ->options(
                                        AdditionalFacility::where('is_active', true)
                                            ->orderBy('sort_order')
                                            ->get()
                                            ->mapWithKeys(fn ($f) => [$f->id => $f->getTranslation('name', 'ar') . ' / ' . $f->getTranslation('name', 'en') . ' - ' . number_format($f->price, 2) . ' ر.س'])
                                    )
                                    ->required()
                                    ->searchable()
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        if ($state) {
                                            $facility = AdditionalFacility::find($state);
                                            if ($facility) {
                                                $set('unit_price', $facility->price);
                                            }
                                        }
                                    }),
                                TextInput::make('quantity')
                                    ->label('العدد')
                                    ->numeric()
                                    ->default(1)
                                    ->minValue(0)
                                    ->required()
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set, $get) {
                                        $unitPrice = $get('unit_price') ?? 0;
                                        $set('total_price', round($state * $unitPrice, 2));
                                    }),
                                TextInput::make('unit_price')
                                    ->label('سعر الوحدة')
                                    ->numeric()
                                    ->prefix('ر.س')
                                    ->disabled()
                                    ->dehydrated(true)
                                    ->default(0),
                                TextInput::make('total_price')
                                    ->label('الإجمالي')
                                    ->numeric()
                                    ->prefix('ر.س')
                                    ->disabled()
                                    ->dehydrated(true)
                                    ->default(0),
                            ])
                            ->columns(4)
                            ->addActionLabel('إضافة مرفق')
                            ->defaultItems(0)
                            ->reorderable(false)
                            ->columnSpanFull(),
                    ]),

                Section::make('تواريخ الاشتراك')
                    ->description('تواريخ بداية ونهاية الاشتراك')
                    ->components([
                        DatePicker::make('start_date')
                            ->label('تاريخ البداية')
                            ->required()
                            ->default(now()->toDateString())
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, $get) {
                                if ($state && $get('package_id')) {
                                    $package = \App\Models\Package::find($get('package_id'));
                                    if ($package) {
                                        $endDate = Carbon::parse($state)->addDays($package->duration_days)->toDateString();
                                        $set('end_date', $endDate);
                                    }
                                }
                            })
                            ->native(false),
                        DatePicker::make('end_date')
                            ->label('تاريخ الانتهاء')
                            ->required()
                            ->native(false)
                            ->helperText('يتم حساب تاريخ الانتهاء تلقائياً بناءً على مدة الباقة'),
                    ])->columns(2),

                Section::make('حالة الاشتراك والدفع')
                    ->components([
                        Select::make('status')
                            ->label('حالة الاشتراك')
                            ->options([
                                'active' => 'نشط',
                                'expired' => 'منتهي',
                                'cancelled' => 'ملغي',
                                'suspended' => 'معلق',
                            ])
                            ->required()
                            ->default('active')
                            ->native(false),
                        Select::make('payment_method')
                            ->label('طريقة الدفع')
                            ->options([
                                'cash' => 'كاش',
                                'visa' => 'فيزا',
                                'mastercard' => 'ماستركارد',
                                'mada' => 'مدى',
                                'transfer' => 'تحويل بنكي',
                                'other' => 'أخرى',
                            ])
                            ->native(false)
                            ->searchable(),
                        Select::make('payment_status')
                            ->label('حالة الدفع')
                            ->options([
                                'paid' => 'مدفوع',
                                'pending' => 'معلق',
                                'refunded' => 'مسترد',
                            ])
                            ->required()
                            ->default('pending')
                            ->native(false),
                        TextInput::make('amount_paid')
                            ->label('المبلغ المدفوع')
                            ->numeric()
                            ->prefix('ر.س')
                            ->step(0.01)
                            ->default(0)
                            ->required(),
                    ])->columns(2),

                Section::make('ملاحظات')
                    ->components([
                        Textarea::make('notes')
                            ->label('ملاحظات')
                            ->rows(3)
                            ->columnSpanFull()
                            ->placeholder('أي ملاحظات إضافية حول الاشتراك...'),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('client.name')
                    ->label('العميل')
                    ->searchable()
                    ->sortable()
                    ->weight('bold'),
                Tables\Columns\TextColumn::make('package.name')
                    ->label('الباقة')
                    ->formatStateUsing(fn ($record) => $record->package ? ($record->package->getTranslation('name', 'ar') . ' / ' . $record->package->getTranslation('name', 'en')) : '-')
                    ->badge()
                    ->color(fn (Subscription $record): string => match ($record->package->color ?? '#f97316') {
                        '#f97316' => 'warning',
                        '#eab308' => 'warning',
                        '#a855f7' => 'success',
                        default => 'info',
                    })
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('propertyTypes.name')
                    ->label('نوع العقار')
                    ->formatStateUsing(fn ($state, $record) => $record->propertyTypes->map(fn ($pt) => $pt->getTranslation('name', 'ar') . ' (' . $pt->pivot->quantity . ')')->implode(', '))
                    ->badge()
                    ->color('primary')
                    ->default('-'),
                Tables\Columns\TextColumn::make('facilities_summary')
                    ->label('المرافق')
                    ->state(fn (Subscription $record) => $record->facilities->count() > 0
                        ? $record->facilities->map(fn ($f) => $f->getTranslation('name', 'ar') . ' (' . $f->pivot->quantity . ')')->implode(', ')
                        : '-'
                    )
                    ->limit(40)
                    ->tooltip(fn (Subscription $record) => $record->facilities->map(fn ($f) => $f->getTranslation('name', 'ar') . ' × ' . $f->pivot->quantity . ' = ' . number_format($f->pivot->total_price, 2) . ' ر.س')->implode("\n"))
                    ->toggleable(isToggledHiddenByDefault: false),
                Tables\Columns\TextColumn::make('package.duration_days')
                    ->label('نوع الاشتراك')
                    ->formatStateUsing(fn ($state): string => match ((int)$state) {
                        365 => 'سنوي',
                        180 => 'نصف سنوي',
                        default => $state . ' يوم',
                    })
                    ->badge()
                    ->color(fn ($state): string => match ((int)$state) {
                        365 => 'success',
                        180 => 'info',
                        default => 'gray',
                    })
                    ->sortable()
                    ->icon(fn ($state): string => match ((int)$state) {
                        365 => 'heroicon-o-calendar-days',
                        180 => 'heroicon-o-calendar',
                        default => 'heroicon-o-clock',
                    })
                    ->toggleable(isToggledHiddenByDefault: true),
                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 =>
                        ($record->status === 'expired' || ($record->end_date < now()->toDateString() && $record->status === 'active'))
                            ? 'danger'
                            : ($record->end_date <= now()->addDays(7)->toDateString() ? 'warning' : 'success')
                    ),
                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';
                    })
                    ->sortable(query: function ($query, string $direction) {
                        return $query->orderByRaw("DATEDIFF(end_date, CURDATE()) {$direction}");
                    }),
                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_method')
                    ->label('طريقة الدفع')
                    ->formatStateUsing(fn (?string $state): string => match ($state) {
                        'cash' => 'كاش',
                        'visa' => 'فيزا',
                        'mastercard' => 'ماستركارد',
                        'mada' => 'مدى',
                        'transfer' => 'تحويل بنكي',
                        'other' => 'أخرى',
                        default => '-',
                    })
                    ->badge()
                    ->color('info')
                    ->toggleable(isToggledHiddenByDefault: true),
                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',
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('تاريخ الإنشاء')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->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('كل حالات الدفع'),

                Tables\Filters\SelectFilter::make('property_type')
                    ->label('🏠 نوع العقار')
                    ->options(
                        PropertyType::where('is_active', true)
                            ->get()
                            ->mapWithKeys(fn ($pt) => [$pt->id => $pt->getTranslation('name', 'ar')])
                    )
                    ->query(fn ($query, array $data) => $data['value']
                        ? $query->whereHas('propertyTypes', fn ($q) => $q->where('property_type_id', $data['value']))
                        : $query
                    )
                    ->placeholder('كل أنواع العقارات'),
            ])
            ->actions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->bulkActions([
                DeleteBulkAction::make(),
                BulkAction::make('export_excel')
                    ->label('تصدير Excel')
                    ->icon('heroicon-o-arrow-down-tray')
                    ->color('success')
                    ->action(function ($records) {
                        $subscriptions = $records->load(['client', 'package', 'propertyTypes', 'facilities']);
                        return Excel::download(new SubscriptionsExport($subscriptions), 'subscriptions-' . now()->format('Y-m-d') . '.xlsx');
                    }),
                BulkAction::make('export_pdf')
                    ->label('تصدير PDF')
                    ->icon('heroicon-o-document-arrow-down')
                    ->color('danger')
                    ->action(function ($records) {
                        $subscriptions = $records->load(['client', 'package', 'propertyTypes', 'facilities']);
                        $pdf = Pdf::loadView('exports.subscriptions-pdf', ['subscriptions' => $subscriptions])
                            ->setPaper('a4', 'landscape')
                            ->setOption('isRemoteEnabled', true);
                        return response()->streamDownload(function () use ($pdf) {
                            echo $pdf->output();
                        }, 'subscriptions-' . now()->format('Y-m-d') . '.pdf');
                    }),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListSubscriptions::route('/'),
            'create' => Pages\CreateSubscription::route('/create'),
            'edit' => Pages\EditSubscription::route('/{record}/edit'),
        ];
    }
}
