<?php

namespace App\Filament\Resources\Customers\Tables;

use App\Jobs\SendWhatsAppMessageJob;
use App\Jobs\SendWhatsAppGatewayMessageJob;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class CustomersTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->applyTenantScope()
            ->columns([
                TextColumn::make('code')
                    ->label(__('filament/admin/customer_resource.code'))
                    ->searchable()
                    ->sortable(),
                TextColumn::make('name')
                    ->label(__('filament/admin/customer_resource.name'))
                    ->searchable()
                    ->sortable(),
                TextColumn::make('tenant.name')
                    ->label('المؤسسة')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->visible(fn() => auth()->user()?->hasRole('super_admin') ?? false),
                TextColumn::make('email')
                    ->label(__('filament/admin/customer_resource.email'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: false),
                TextColumn::make('phone')
                    ->label(__('filament/admin/customer_resource.phone'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: false),
                TextColumn::make('credit_limit')
                    ->label(__('filament/admin/customer_resource.credit_limit'))
                    ->money('EGP')
                    ->sortable()
                    ->summarize([
                        \Filament\Tables\Columns\Summarizers\Sum::make()
                            ->label(__('filament/admin/customer_resource.total_credit_limit')),
                    ]),
                TextColumn::make('current_balance')
                    ->label(__('filament/admin/customer_resource.current_balance'))
                    ->money('EGP')
                    ->sortable()
                    ->getStateUsing(function ($record) {
                        // حساب الرصيد الحالي بشكل ديناميكي
                        $totalSales = $record->sales()->sum('total_amount');
                        $totalPaid = $record->sales()->sum('paid_amount');
                        $totalPayments = \App\Models\CustomerPayment::where('customer_id', $record->id)
                            ->where('status', 'confirmed')
                            ->sum('amount');

                        return ($record->opening_balance ?? 0) + $totalSales - $totalPaid - $totalPayments;
                    })
                    ->summarize([
                        \Filament\Tables\Columns\Summarizers\Sum::make()
                            ->label(__('filament/admin/customer_resource.total_balance')),
                    ]),
                TextColumn::make('last_transaction_date')
                    ->label('تاريخ آخر معاملة')
                    ->getStateUsing(function ($record) {
                        $lastSale = $record->sales()->latest('created_at')->first();
                        $lastPayment = \App\Models\CustomerPayment::where('customer_id', $record->id)
                            ->latest('created_at')
                            ->first();

                        $lastDate = null;
                        if ($lastSale && $lastPayment) {
                            $lastDate = $lastSale->created_at->gt($lastPayment->created_at)
                                ? $lastSale->created_at
                                : $lastPayment->created_at;
                        } elseif ($lastSale) {
                            $lastDate = $lastSale->created_at;
                        } elseif ($lastPayment) {
                            $lastDate = $lastPayment->created_at;
                        }

                        return $lastDate?->format('Y-m-d');
                    })
                    ->sortable()
                    ->placeholder('لا توجد معاملات')
                    ->toggleable(isToggledHiddenByDefault: false),
                IconColumn::make('is_active')
                    ->label(__('filament/admin/customer_resource.is_active'))
                    ->boolean()
                    ->sortable(),
                TextColumn::make('createdBy.name')
                    ->label(__('filament/admin/customer_resource.created_by'))
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false),
                TextColumn::make('updatedBy.name')
                    ->label(__('filament/admin/customer_resource.updated_by'))
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false),
                TextColumn::make('created_at')
                    ->label(__('filament/admin/customer_resource.created_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('updated_at')
                    ->label(__('filament/admin/customer_resource.updated_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('tenant_id')
                    ->label('المؤسسة')
                    ->relationship('tenant', 'name')
                    ->searchable()
                    ->preload()
                    ->visible(fn() => auth()->user()?->hasRole('super_admin') ?? false),
            ])
            ->recordActions([
                Action::make('view_statement')
                    ->label('كشف حساب')
                    ->icon('heroicon-o-document-text')
                    ->color('primary')
                    ->url(fn($record) => \App\Filament\Pages\CustomerStatementReport::getUrl(['customer_id' => $record->id]))
                    ->openUrlInNewTab(),
                EditAction::make()
                    ->visible(fn() => !auth()->user()?->is_system_admin || auth()->user()?->is_tenant_owner),
                Action::make('send_whatsapp')
                    ->label(__('filament/admin/customer_resource.send_whatsapp'))
                    ->icon('heroicon-o-chat-bubble-left-right')
                    ->color('success')
                    ->form([
                        Textarea::make('message')
                            ->label(__('filament/admin/customer_resource.whatsapp_message'))
                            ->placeholder(__('filament/admin/customer_resource.whatsapp_message_placeholder'))
                            ->required()
                            ->rows(5)
                            ->maxLength(1000),
                    ])
                    ->action(function ($record, array $data) {
                        if (empty($record->phone)) {
                            Notification::make()
                                ->title(__('filament/admin/customer_resource.no_phone'))
                                ->danger()
                                ->send();
                            return;
                        }

                        SendWhatsAppMessageJob::dispatch(
                            $record->phone,
                            $data['message'],
                            ['customer_id' => $record->id, 'customer_name' => $record->name]
                        );

                        Notification::make()
                            ->title(__('filament/admin/customer_resource.whatsapp_queued'))
                            ->success()
                            ->send();
                    })
                    ->visible(fn($record) => !empty($record->phone) && config('twilio.enabled')),
                Action::make('send_whatsapp_gateway')
                    ->label(__('filament/admin/customer_resource.send_whatsapp_gateway'))
                    ->icon('heroicon-o-device-phone-mobile')
                    ->color('info')
                    ->form([
                        Textarea::make('message')
                            ->label(__('filament/admin/customer_resource.whatsapp_message'))
                            ->placeholder(__('filament/admin/customer_resource.whatsapp_message_placeholder'))
                            ->required()
                            ->rows(5)
                            ->maxLength(1000),
                    ])
                    ->action(function ($record, array $data) {
                        if (empty($record->phone)) {
                            Notification::make()
                                ->title(__('filament/admin/customer_resource.no_phone'))
                                ->danger()
                                ->send();
                            return;
                        }

                        SendWhatsAppGatewayMessageJob::dispatch(
                            $record->phone,
                            $data['message'],
                            ['customer_id' => $record->id, 'customer_name' => $record->name]
                        );

                        Notification::make()
                            ->title(__('filament/admin/customer_resource.whatsapp_gateway_queued'))
                            ->success()
                            ->send();
                    })
                    ->visible(fn($record) => !empty($record->phone) && config('whatsapp-gateway.enabled')),
                Action::make('send_quick_message')
                    ->label(__('filament/admin/customer_resource.send_quick_message'))
                    ->icon('heroicon-o-paper-airplane')
                    ->color('warning')
                    ->requiresConfirmation()
                    ->modalHeading(__('filament/admin/customer_resource.send_quick_message'))
                    ->modalDescription(fn($record) => __('filament/admin/customer_resource.send_quick_message_description', ['name' => $record->name]))
                    ->modalSubmitActionLabel(__('filament/admin/customer_resource.send_now'))
                    ->action(function ($record) {
                        if (empty($record->phone)) {
                            Notification::make()
                                ->title(__('filament/admin/customer_resource.no_phone'))
                                ->danger()
                                ->send();
                            return;
                        }

                        // استخدام رسالة الترحيب من الإعدادات
                        $template = config('whatsapp-gateway.quick_messages.greeting');
                        $message = str_replace(
                            ['{name}', '{balance}', '{credit_limit}'],
                            [$record->name, number_format($record->current_balance, 2), number_format($record->credit_limit, 2)],
                            $template
                        );

                        SendWhatsAppGatewayMessageJob::dispatch(
                            $record->phone,
                            $message,
                            ['customer_id' => $record->id, 'type' => 'quick_greeting']
                        );

                        Notification::make()
                            ->title(__('filament/admin/customer_resource.quick_message_sent'))
                            ->body($message)
                            ->success()
                            ->send();
                    })
                    ->visible(fn($record) => !empty($record->phone) && config('whatsapp-gateway.enabled')),
                Action::make('send_reminder')
                    ->label(__('filament/admin/customer_resource.send_reminder'))
                    ->icon('heroicon-o-bell-alert')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->modalHeading(__('filament/admin/customer_resource.send_reminder'))
                    ->modalDescription(fn($record) => __('filament/admin/customer_resource.send_reminder_description', ['name' => $record->name, 'balance' => number_format($record->current_balance, 2)]))
                    ->modalSubmitActionLabel(__('filament/admin/customer_resource.send_now'))
                    ->action(function ($record) {
                        if (empty($record->phone)) {
                            Notification::make()
                                ->title(__('filament/admin/customer_resource.no_phone'))
                                ->danger()
                                ->send();
                            return;
                        }

                        // استخدام رسالة التذكير من الإعدادات
                        $template = config('whatsapp-gateway.quick_messages.reminder');
                        $message = str_replace(
                            ['{name}', '{balance}', '{credit_limit}'],
                            [$record->name, number_format($record->current_balance, 2), number_format($record->credit_limit, 2)],
                            $template
                        );

                        SendWhatsAppGatewayMessageJob::dispatch(
                            $record->phone,
                            $message,
                            ['customer_id' => $record->id, 'type' => 'reminder']
                        );

                        Notification::make()
                            ->title(__('filament/admin/customer_resource.reminder_sent'))
                            ->body($message)
                            ->success()
                            ->send();
                    })
                    ->visible(fn($record) => !empty($record->phone) && config('whatsapp-gateway.enabled') && $record->current_balance > 0),
                DeleteAction::make()
                    ->requiresConfirmation()
                    ->hidden(fn() => \App\Models\Customer::count() <= 1),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->hidden(fn() => \App\Models\Customer::count() <= 1),
                ]),
            ]);
    }
}
