<?php

namespace App\Actions;

use Filament\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use App\Services\ExcelService;

class ImportExcelAction extends Action
{
    protected $importClass;
    protected $onSuccessCallback;
    protected $onErrorCallback;

    public static function makeImport($importClass): static
    {
        $action = static::make('import_excel');
        $action->importClass = $importClass;
        return $action;
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this
            ->label('Importer Excel')
            ->icon('heroicon-o-arrow-up-tray')
            ->color('success')
            ->form([
                FileUpload::make('file')
                    ->label('Fichier Excel')
                    ->acceptedFileTypes(['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel', 'text/csv'])
                    ->maxSize(10240)
                    ->required()
                    ->helperText('Formats acceptés: XLSX, XLS, CSV. Taille max: 10MB'),
            ])
            ->action(function (array $data) {
                try {
                    $file = $data['file'];
                    $excelService = app(ExcelService::class);
                    
                    // Validate file
                    $excelService->validateFile($file);
                    
                    // Store file
                    $storedPath = $excelService->storeFile($file);
                    
                    // Import
                    $results = $excelService->import($file, $this->importClass, [
                        'update_existing' => false,
                        'skip_duplicates' => true,
                    ]);
                    
                    // Show notification
                    $this->showImportNotification($results);
                    
                    // Call success callback if provided
                    if ($this->onSuccessCallback) {
                        call_user_func($this->onSuccessCallback, $results);
                    }
                    
                    // Refresh page
                    $this->redirect(request()->header('referer'));
                    
                } catch (\Exception $e) {
                    Log::error('Import action failed', [
                        'error' => $e->getMessage(),
                        'import_class' => $this->importClass,
                    ]);
                    
                    Notification::make()
                        ->danger()
                        ->title('Erreur lors de l\'import')
                        ->body($e->getMessage())
                        ->send();
                    
                    if ($this->onErrorCallback) {
                        call_user_func($this->onErrorCallback, $e);
                    }
                }
            });
    }

    protected function showImportNotification($results)
    {
        $successCount = $results['success_count'] ?? 0;
        $errorCount = $results['error_count'] ?? 0;
        $updatedCount = $results['updated_count'] ?? 0;
        $skippedCount = $results['skipped_count'] ?? 0;
        
        $message = "Import terminé:\n";
        $message .= "- Succès: $successCount\n";
        $message .= "- Mise à jour: $updatedCount\n";
        $message .= "- Ignorés: $skippedCount\n";
        $message .= "- Erreurs: $errorCount";
        
        if ($errorCount > 0 && !empty($results['errors'])) {
            $message .= "\n\nDétails des erreurs:\n";
            foreach (array_slice($results['errors'], 0, 5) as $error) {
                $message .= "- " . json_encode($error) . "\n";
            }
            if (count($results['errors']) > 5) {
                $message .= "... et " . (count($results['errors']) - 5) . " autres erreurs";
            }
        }
        
        Notification::make()
            ->title('Import Excel')
            ->body($message)
            ->success()
            ->persistent()
            ->send();
    }

    public function onSuccess(callable $callback): self
    {
        $this->onSuccessCallback = $callback;
        return $this;
    }

    public function onError(callable $callback): self
    {
        $this->onErrorCallback = $callback;
        return $this;
    }

    public function updateExisting(bool $update = true): self
    {
        // This would be used in the action form
        return $this;
    }

    public function skipDuplicates(bool $skip = true): self
    {
        // This would be used in the action form
        return $this;
    }
}
