<?php

namespace App\Extensions\Installed\Importer\Livewire\Csv;

use Livewire\Component;
use App\Extensions\Installed\Importer\Models\ImportJob;
use App\Extensions\Installed\Importer\Services\CsvImporter;

class Process extends Component
{
    public $jobId;
    public $job;
    public $importing = false;
    public $completed = false;
    public $results = [];
    public $dryRunning = false;
    public $dryRunCompleted = false;
    public $dryRunResults = [];

    public function mount($jobId)
    {
        $this->jobId = $jobId;
        $this->job = ImportJob::findOrFail($jobId);

        // Check if already completed
        if ($this->job->status === 'completed') {
            $this->completed = true;
            $this->results = [
                'type' => $this->job->type,
                'imported' => $this->job->processed_rows,
                'skipped' => $this->job->failed_rows,
                'errors' => $this->job->errors ?? [],
            ];
        }

        // Load dry run results if they exist
        if (!empty($this->job->options['dry_run_results'])) {
            $this->dryRunCompleted = true;
            $this->dryRunResults = $this->job->options['dry_run_results'];
        }
    }

    public function runDryRun()
    {
        try {
            $this->dryRunning = true;

            // Create importer with dry_run enabled
            $options = array_merge($this->job->options ?? [], ['dry_run' => true]);

            $importer = new CsvImporter(
                $this->job->file_path,
                $this->job->type,
                $this->job->field_mapping ?? [],
                $options
            );

            // Run validation
            $this->dryRunResults = $importer->import();

            // Save dry run results to job options
            $jobOptions = $this->job->options ?? [];
            $jobOptions['dry_run_results'] = $this->dryRunResults;

            $this->job->update([
                'options' => $jobOptions,
            ]);

            $this->dryRunCompleted = true;
            $this->dryRunning = false;

            if ($this->dryRunResults['skipped'] === 0) {
                session()->flash('success', 'Validation passed! All rows are valid and ready to import.');
            } else {
                session()->flash('warning', sprintf(
                    'Validation completed with %d errors. Review the errors below before importing.',
                    $this->dryRunResults['skipped']
                ));
            }
        } catch (\Exception $e) {
            $this->dryRunning = false;
            session()->flash('error', 'Validation failed: ' . $e->getMessage());
        }
    }

    public function startImport()
    {
        try {
            $this->importing = true;
            $this->job->start();

            // Create importer
            $importer = new CsvImporter(
                $this->job->file_path,
                $this->job->type,
                $this->job->field_mapping ?? [],
                $this->job->options ?? []
            );

            // Run import
            $this->results = $importer->import();

            // Update job
            $this->job->update([
                'status' => 'completed',
                'processed_rows' => $this->results['imported'],
                'failed_rows' => $this->results['skipped'],
                'errors' => $this->results['errors'],
                'completed_at' => now(),
                'result_summary' => sprintf(
                    "Imported %d %s. %d failed.",
                    $this->results['imported'],
                    $this->job->type,
                    $this->results['skipped']
                ),
            ]);

            $this->completed = true;
            $this->importing = false;

            session()->flash('success', 'Import completed successfully!');
        } catch (\Exception $e) {
            $this->job->fail($e->getMessage());
            $this->importing = false;
            session()->flash('error', 'Import failed: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('extension.importer::csv.process');
    }
}
