<?php

namespace App\Filament\Pages;

use App\Services\UpworkEarningsImporter;
use Filament\Forms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Storage;

class UpworkImportPage extends Page implements HasForms
{
    use InteractsWithForms;

    protected static ?string $navigationIcon  = 'heroicon-o-arrow-up-tray';
    protected static ?string $navigationGroup = 'Comercial';
    protected static ?string $navigationLabel = 'Importar Upwork';
    protected static ?string $title           = 'Importar pagos de Upwork';
    protected static ?int    $navigationSort  = 10;
    protected static string  $view            = 'filament.pages.upwork-import';

    // ── Estado del wizard ─────────────────────────────────────────────────────
    public string $step = 'upload';  // upload | preview | done

    public ?array $data          = [];
    public array  $previewNew    = [];
    public array  $previewDups   = [];
    public array  $previewInvalid = [];

    public function mount(): void
    {
        $this->form->fill();
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Seleccionar archivo CSV')
                    ->description('Descarga desde Upwork → Reports → Transaction History → Export to CSV')
                    ->schema([
                        Forms\Components\FileUpload::make('csv_file')
                            ->label('Transaction History (*.csv)')
                            ->disk('local')
                            ->directory('upwork-imports')
                            ->acceptedFileTypes([
                                'text/csv', 'text/plain',
                                'application/csv', 'application/octet-stream',
                            ])
                            ->maxSize(2048)
                            ->required()
                            ->helperText(
                                'Formato: Date, Transaction ID, Transaction type, Transaction summary, ...'
                            ),
                    ]),
            ])
            ->statePath('data');
    }

    // ── Paso 1: Analizar ──────────────────────────────────────────────────────

    public function analyze(): void
    {
        $data = $this->form->getState();

        $filePath = Storage::disk('local')->path($data['csv_file']);

        if (!file_exists($filePath)) {
            Notification::make()->title('Error')->body('No se pudo leer el archivo.')->danger()->send();
            return;
        }

        $content  = file_get_contents($filePath);
        Storage::disk('local')->delete($data['csv_file']); // Limpiamos ya

        $importer = new UpworkEarningsImporter();
        $result   = $importer->analyze($content);

        $this->previewNew     = $result['new'];
        $this->previewDups    = $result['duplicates'];
        $this->previewInvalid = $result['invalid'];
        $this->step           = 'preview';
    }

    // ── Paso 2: Confirmar importación ─────────────────────────────────────────

    public function confirmImport(): void
    {
        if (empty($this->previewNew)) {
            Notification::make()
                ->title('Nada que importar')
                ->body('Todos los registros ya existen.')
                ->warning()
                ->send();
            $this->resetWizard();
            return;
        }

        $importer = new UpworkEarningsImporter();
        $result   = $importer->import($this->previewNew, auth()->user());

        $parts = ["Pagos registrados: {$result['created']}"];
        if ($result['sales_created'] > 0) {
            $parts[] = "Ventas creadas: {$result['sales_created']}";
        }
        if ($result['clients_created'] > 0) {
            $parts[] = "Clientes nuevos: {$result['clients_created']}";
        }
        if (!empty($this->previewDups)) {
            $parts[] = "Duplicados omitidos: " . count($this->previewDups);
        }

        Notification::make()
            ->title('Importación completada')
            ->body(implode(' | ', $parts))
            ->success()
            ->persistent()
            ->send();

        if (!empty($result['errors'])) {
            Notification::make()
                ->title('Algunos registros fallaron')
                ->body(implode("\n", array_slice($result['errors'], 0, 5)))
                ->warning()
                ->persistent()
                ->send();
        }

        $this->step = 'done';
    }

    // ── Cancelar / resetear ───────────────────────────────────────────────────

    public function resetWizard(): void
    {
        $this->step           = 'upload';
        $this->previewNew     = [];
        $this->previewDups    = [];
        $this->previewInvalid = [];
        $this->form->fill();
    }
}
