<?php

namespace App\Actions;

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

class ExportExcelAction extends Action
{
    protected $exportClass;
    protected $excelService;
    protected $filename;
    protected $query;
    protected $filters;

    public static function makeExport($exportClass, $filename = null): static
    {
        $action = static::make('export_excel');
        $action->exportClass = $exportClass;
        $action->filename = $filename;
        $action->excelService = app(ExcelService::class);
        return $action;
    }

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

        $this
            ->label('Exporter Excel')
            ->icon('heroicon-o-arrow-down-tray')
            ->color('primary')
            ->action(function () {
                try {
                    $filename = $this->filename ?? 'export_' . date('Y-m-d_His') . '.xlsx';
                    
                    Log::info('Starting Excel export action', [
                        'export_class' => $this->exportClass,
                        'filename' => $filename,
                    ]);
                    
                    return $this->excelService->export($this->exportClass, $filename, [
                        'query' => $this->query,
                        'filters' => $this->filters,
                    ]);
                    
                } catch (\Exception $e) {
                    Log::error('Export action failed', [
                        'error' => $e->getMessage(),
                        'export_class' => $this->exportClass,
                    ]);
                    
                    Notification::make()
                        ->danger()
                        ->title('Erreur lors de l\'export')
                        ->body($e->getMessage())
                        ->send();
                }
            });
    }

    public function withQuery($query): self
    {
        $this->query = $query;
        return $this;
    }

    public function withFilters(array $filters): self
    {
        $this->filters = $filters;
        return $this;
    }

    public function withFilename($filename): self
    {
        $this->filename = $filename;
        return $this;
    }
}
