<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ClientResource\Pages;
use App\Models\Client;
use App\Models\Package;
use App\Models\PropertyType;
use App\Exports\ClientsExport;
use Filament\Actions\BulkAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
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\Columns\SpatieMediaLibraryImageColumn;
use Filament\Tables\Table;

class ClientResource extends Resource
{
    protected static ?string $model = Client::class;

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-user-circle';

    protected static ?string $navigationLabel = 'العملاء';

    protected static ?string $modelLabel = 'عميل';

    protected static ?string $pluralModelLabel = 'العملاء';

    protected static string | \UnitEnum | null $navigationGroup = 'إدارة العملاء';

    protected static ?int $navigationSort = 1;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('الصورة الشخصية')
                    ->components([
                        SpatieMediaLibraryFileUpload::make('profile_photo')
                            ->label('صورة العميل')
                            ->collection('profile_photo')
                            ->image()
                            ->avatar()
                            ->maxSize(2048)
                            ->columnSpanFull(),
                    ]),
                Section::make('البيانات الشخصية')
                    ->components([
                        TextInput::make('name')
                            ->label('الاسم الكامل')
                            ->required()
                            ->maxLength(255),
                        TextInput::make('email')
                            ->label('البريد الإلكتروني')
                            ->email()
                            ->required()
                            ->maxLength(255)
                            ->unique(ignoreRecord: true),
                        TextInput::make('phone')
                            ->label('رقم الهاتف')
                            ->tel()
                            ->maxLength(255),
                        Select::make('gender')
                            ->label('الجنس')
                            ->options([
                                'Male' => 'ذكر',
                                'Female' => 'أنثى',
                            ])
                            ->native(false),
                        DatePicker::make('birth_date')
                            ->label('تاريخ الميلاد')
                            ->displayFormat('F d, Y')
                            ->native(false),
                    ])->columns(2),
                Section::make('العنوان')
                    ->components([
                        TextInput::make('address')
                            ->label('العنوان')
                            ->maxLength(255),
                        TextInput::make('city')
                            ->label('المدينة')
                            ->maxLength(255),
                    ])->columns(2),
                Section::make('معلومات إضافية')
                    ->components([
                        Checkbox::make('is_active')
                            ->label('نشط')
                            ->default(true),
                        Textarea::make('notes')
                            ->label('ملاحظات')
                            ->rows(3)
                            ->columnSpanFull(),
                        TextInput::make('fcm_token')
                            ->label('FCM Token')
                            ->placeholder('FCM Token للإشعارات')
                            ->helperText('Token المستخدم لإرسال الإشعارات للموبايل')
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) => $query->with([
                'subscriptions' => function ($q) {
                    $q->where('status', 'active')
                        ->where('end_date', '>=', now()->toDateString())
                        ->with('package');
                },
                'pointBalance'
            ]))
            ->columns([
                SpatieMediaLibraryImageColumn::make('profile_photo')
                    ->label('الصورة')
                    ->collection('profile_photo')
                    ->circular()
                    ->defaultImageUrl(fn () => 'https://ui-avatars.com/api/?name=C&background=3b82f6&color=fff'),
                Tables\Columns\TextColumn::make('name')
                    ->label('الاسم')
                    ->searchable()
                    ->sortable()
                    ->weight('bold'),
                Tables\Columns\TextColumn::make('email')
                    ->label('البريد الإلكتروني')
                    ->searchable()
                    ->sortable()
                    ->icon('heroicon-o-envelope'),
                Tables\Columns\TextColumn::make('phone')
                    ->label('رقم الهاتف')
                    ->searchable()
                    ->icon('heroicon-o-phone'),
                Tables\Columns\TextColumn::make('city')
                    ->label('المدينة')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('gender')
                    ->label('الجنس')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'Male' => 'ذكر',
                        'Female' => 'أنثى',
                        default => $state,
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'Male' => 'info',
                        'Female' => 'success',
                        default => 'gray',
                    }),
                Tables\Columns\IconColumn::make('is_active')
                    ->label('نشط')
                    ->boolean(),
                Tables\Columns\TextColumn::make('points_balance')
                    ->label('رصيد النقاط')
                    ->suffix(' نقطة')
                    ->badge()
                    ->color('warning')
                    ->default(0)
                    ->sortable(),
                Tables\Columns\TextColumn::make('active_subscription.package.name')
                    ->label('الباقة الحالية')
                    ->badge()
                    ->color('success')
                    ->default('-')
                    ->formatStateUsing(fn ($state, $record) => $record->active_subscription?->package ? ($record->active_subscription->package->getTranslation('name', 'ar') . ' / ' . $record->active_subscription->package->getTranslation('name', 'en')) : '-'),
                Tables\Columns\TextColumn::make('active_subscription.end_date')
                    ->label('ينتهي في')
                    ->formatStateUsing(function ($state) {
                        if (!$state) {
                            return '-';
                        }
                        $date = $state instanceof \Carbon\Carbon ? $state : \Carbon\Carbon::parse($state);
                        return $date->format('Y-m-d');
                    })
                    ->color(function ($state, $record) {
                        $subscription = $record->active_subscription;
                        if (!$subscription || !$subscription->end_date) {
                            return 'gray';
                        }
                        $endDate = $subscription->end_date instanceof \Carbon\Carbon 
                            ? $subscription->end_date 
                            : \Carbon\Carbon::parse($subscription->end_date);
                        return $endDate->toDateString() < now()->addDays(7)->toDateString() ? 'warning' : 'success';
                    }),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('تاريخ التسجيل')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                // === حالة الاشتراك ===
                Tables\Filters\Filter::make('has_active_subscription')
                    ->label('✅ لديه اشتراك نشط')
                    ->query(fn ($query) => $query->whereHas('subscriptions', fn ($q) =>
                        $q->where('status', 'active')
                            ->where('end_date', '>=', now()->toDateString())
                    )),

                Tables\Filters\Filter::make('no_subscription')
                    ->label('🚫 بدون اشتراك')
                    ->query(fn ($query) => $query->whereDoesntHave('subscriptions')),

                Tables\Filters\Filter::make('expired_subscription')
                    ->label('❌ اشتراك منتهي')
                    ->query(fn ($query) => $query
                        ->whereHas('subscriptions')
                        ->whereDoesntHave('subscriptions', fn ($q) =>
                            $q->where('status', 'active')
                                ->where('end_date', '>=', now()->toDateString())
                        )
                    ),

                Tables\Filters\Filter::make('expiring_soon')
                    ->label('⚠️ اشتراك ينتهي خلال 7 أيام')
                    ->query(fn ($query) => $query->whereHas('subscriptions', fn ($q) =>
                        $q->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->whereHas('subscriptions', fn ($q) =>
                        $q->where('status', 'active')
                            ->where('end_date', '>=', now()->toDateString())
                            ->where('end_date', '<=', now()->addDays(30)->toDateString())
                    )),

                // === الباقة ===
                Tables\Filters\SelectFilter::make('package')
                    ->label('📦 الباقة')
                    ->options(
                        Package::where('is_active', true)
                            ->get()
                            ->mapWithKeys(fn ($p) => [$p->id => $p->getTranslation('name', 'ar') . ' / ' . $p->getTranslation('name', 'en')])
                    )
                    ->query(fn ($query, array $data) => $data['value']
                        ? $query->whereHas('subscriptions', fn ($q) =>
                            $q->where('status', 'active')
                                ->where('end_date', '>=', now()->toDateString())
                                ->where('package_id', $data['value'])
                        )
                        : $query
                    )
                    ->placeholder('كل الباقات')
                    ->searchable(),

                // === نوع العقار ===
                Tables\Filters\SelectFilter::make('property_type')
                    ->label('🏠 نوع العقار')
                    ->options(
                        PropertyType::where('is_active', true)
                            ->get()
                            ->mapWithKeys(fn ($pt) => [$pt->id => $pt->getTranslation('name', 'ar') . ' / ' . $pt->getTranslation('name', 'en')])
                    )
                    ->query(fn ($query, array $data) => $data['value']
                        ? $query->whereHas('subscriptions', fn ($q) =>
                            $q->where('status', 'active')
                                ->where('end_date', '>=', now()->toDateString())
                                ->whereHas('propertyTypes', fn ($q2) => $q2->where('property_type_id', $data['value']))
                        )
                        : $query
                    )
                    ->placeholder('كل أنواع العقارات')
                    ->searchable(),

                // === المدينة ===
                Tables\Filters\SelectFilter::make('city')
                    ->label('🏙️ المدينة')
                    ->options(fn () => Client::whereNotNull('city')
                        ->where('city', '!=', '')
                        ->distinct()
                        ->pluck('city', 'city')
                        ->toArray()
                    )
                    ->placeholder('كل المدن')
                    ->searchable(),

                // === الجنس ===
                Tables\Filters\SelectFilter::make('gender')
                    ->label('👤 الجنس')
                    ->options([
                        'Male' => '♂️ ذكر',
                        'Female' => '♀️ أنثى',
                    ])
                    ->placeholder('الكل'),

                // === الحالة ===
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('⚙️ حالة العميل')
                    ->placeholder('الكل')
                    ->trueLabel('نشط فقط')
                    ->falseLabel('غير نشط فقط'),

                // === النقاط ===
                Tables\Filters\Filter::make('has_points')
                    ->label('⭐ لديه نقاط')
                    ->query(fn ($query) => $query->whereHas('pointBalance', fn ($q) =>
                        $q->where('balance', '>', 0)
                    )),

                Tables\Filters\Filter::make('high_points')
                    ->label('🌟 نقاط عالية (500+)')
                    ->query(fn ($query) => $query->whereHas('pointBalance', fn ($q) =>
                        $q->where('balance', '>=', 500)
                    )),
            ])
            ->filtersFormColumns(3)
            ->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) {
                        $clients = $records->load(['subscriptions.package', 'pointBalance']);
                        return Excel::download(new ClientsExport($clients), 'clients-' . now()->format('Y-m-d') . '.xlsx');
                    }),
                BulkAction::make('export_pdf')
                    ->label('تصدير PDF')
                    ->icon('heroicon-o-document-arrow-down')
                    ->color('danger')
                    ->action(function ($records) {
                        $clients = $records->load(['subscriptions.package', 'pointBalance']);
                        $pdf = Pdf::loadView('exports.clients-pdf', ['clients' => $clients])
                            ->setPaper('a4', 'landscape')
                            ->setOption('isRemoteEnabled', true);
                        return response()->streamDownload(function () use ($pdf) {
                            echo $pdf->output();
                        }, 'clients-' . now()->format('Y-m-d') . '.pdf');
                    }),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

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

