<?php

use App\Extensions\Installed\Importer\Models\ImportJob;
use App\Extensions\Installed\Importer\Services\ChunkedCsvImporter;
use App\Extensions\Installed\Importer\Services\CsvImporter;
use function Livewire\Volt\{state, mount, on};

state([
    'job',
    'progress' => 0,
    'status' => 'pending',
    'stats' => [
        'total' => 0,
        'processed' => 0,
        'failed' => 0,
    ],
    'errors' => [],
    'autoRefresh' => true,
    'dryRunning' => false,
    'dryRunCompleted' => false,
    'dryRunResults' => [],
]);

mount(function (ImportJob $job) {
    $this->job = $job;
    $this->updateStats();

    if (!empty($this->job->options['dry_run_results'])) {
        $this->dryRunCompleted = true;
        $this->dryRunResults = $this->job->options['dry_run_results'];
    }
});

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

        $options = array_merge($this->job->options ?? [], ['dry_run' => true]);

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

        $this->dryRunResults = $importer->import();

        $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) > 0) {
            session()->flash('warning', sprintf(
                'Dry run completed with %d issues. Review the errors below before importing.',
                $this->dryRunResults['skipped']
            ));
        } else {
            session()->flash('success', 'Dry run passed — no issues detected. You can safely start the import.');
        }
    } catch (\Exception $e) {
        $this->dryRunning = false;
        session()->flash('error', 'Dry run failed: ' . $e->getMessage());
    }
};

$startImport = function () {
    try {
        $importer = new ChunkedCsvImporter($this->job);

        // Process in chunks
        $result = $importer->process(true); // Process single chunk

        $this->updateStats();

        // Refresh page to continue processing
        if ($this->status === 'processing') {
            $this->dispatch('import-chunk-complete');
        }

    } catch (\Exception $e) {
        session()->flash('error', 'Import failed: ' . $e->getMessage());
        $this->updateStats();
    }
};

$pauseImport = function () {
    $this->job->pause();
    $this->updateStats();
    session()->flash('message', 'Import paused. You can resume it later.');
};

$resumeImport = function () {
    $this->job->resume();
    $this->updateStats();
    $this->startImport();
};

$updateStats = function () {
    $this->job = $this->job->fresh();
    $this->status = $this->job->status;
    $this->progress = $this->job->getProgressPercentage();
    $this->stats = [
        'total' => $this->job->total_rows,
        'processed' => $this->job->processed_rows,
        'failed' => $this->job->failed_rows,
    ];
    $this->errors = $this->job->errors ?? [];
};

on(['import-chunk-complete' => function () {
    if ($this->status === 'processing' && $this->autoRefresh) {
        $this->startImport();
    }
}]);

?>

<div>
    <x-slot name="header">Import Progress</x-slot>

    @volt('extensions.importer.csv.process')
    <div class="space-y-6 pb-16" wire:poll.3s="updateStats">
        <!-- Breadcrumb -->
        <nav class="flex text-sm text-gray-500 dark:text-gray-400" aria-label="Breadcrumb">
            <ol class="inline-flex items-center space-x-1 md:space-x-3">
                <li class="inline-flex items-center">
                    <a href="{{ route('extensions.importer.index') }}"
                       class="inline-flex items-center gap-1 text-gray-600 hover:text-indigo-500 dark:text-gray-300 dark:hover:text-indigo-400 transition">
                        <x-heroicon-o-arrow-uturn-left class="w-4 h-4" />
                        Importer
                    </a>
                </li>
                <li>
                    <div class="flex items-center">
                        <x-heroicon-s-chevron-right class="w-4 h-4 text-gray-400" />
                        <span class="ml-1 text-gray-500 dark:text-gray-400">Import Progress</span>
                    </div>
                </li>
            </ol>
        </nav>
        <!-- Progress -->
        <div class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900">
            <div class="flex items-center justify-between mb-2">
                <span class="text-sm font-medium text-indigo-600">Step 3 of 3</span>
                <span class="text-sm font-medium text-gray-500 dark:text-gray-300">
                    {{ ucfirst($status) }}
                </span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2 dark:bg-gray-800">
                <div class="bg-indigo-600 h-2 rounded-full transition-all duration-300" style="width: {{ $progress }}%"></div>
            </div>
            <div class="mt-2 text-right text-sm text-gray-600 dark:text-gray-300">
                {{ number_format($progress, 1) }}% Complete
            </div>
        </div>

        @if (session('error'))
            <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 rounded-xl px-4 py-3">
                {{ session('error') }}
            </div>
        @endif

        @if (session('success'))
            <div class="bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-200 rounded-xl px-4 py-3">
                {{ session('success') }}
            </div>
        @endif

        @if (session('warning'))
            <div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 text-amber-700 dark:text-amber-200 rounded-xl px-4 py-3">
                {{ session('warning') }}
            </div>
        @endif

        @if (session('message'))
            <div class="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-800 dark:text-green-200 rounded-xl px-4 py-3">
                {{ session('message') }}
            </div>
        @endif

        <!-- Stats -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <x-heroicon-o-document-text class="h-12 w-12 text-indigo-500" />
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500 dark:text-gray-300">Total Rows</p>
                        <p class="text-2xl font-semibold text-gray-900 dark:text-white">{{ number_format($stats['total']) }}</p>
                    </div>
                </div>
            </div>

            <div class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <x-heroicon-o-check-circle class="h-12 w-12 text-green-500" />
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Imported</p>
                        <p class="text-2xl font-semibold text-gray-900 dark:text-white">{{ number_format($stats['processed']) }}</p>
                    </div>
                </div>
            </div>

            <div class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <x-heroicon-o-x-circle class="h-12 w-12 text-red-500" />
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Failed</p>
                        <p class="text-2xl font-semibold text-gray-900 dark:text-white">{{ number_format($stats['failed']) }}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Control Panel -->
        <div class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Import Controls</h3>

            <div class="flex flex-wrap items-center gap-3">
                <button wire:click="runDryRun"
                        wire:loading.attr="disabled"
                        wire:target="runDryRun"
                        @disabled($status === 'processing')
                        class="inline-flex items-center gap-2 rounded-xl border border-indigo-600 bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700 disabled:opacity-60 dark:border-indigo-500 dark:bg-indigo-500 dark:hover:bg-indigo-600">
                    <x-heroicon-s-magnifying-glass class="h-5 w-5" />
                    {{ $dryRunCompleted ? 'Re-run Dry Run' : 'Run Dry Run' }}
                </button>

                @if($status === 'pending')
                    <button wire:click="startImport"
                            class="inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700">
                        <x-heroicon-s-play class="h-5 w-5" />
                        Start Import
                    </button>
                @elseif($status === 'processing')
                    <button wire:click="pauseImport"
                            class="inline-flex items-center gap-2 rounded-xl bg-amber-500 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-amber-600">
                        <x-heroicon-s-pause class="h-5 w-5" />
                        Pause Import
                    </button>
                @elseif($status === 'paused')
                    <button wire:click="resumeImport"
                            class="inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700">
                        <x-heroicon-s-play class="h-5 w-5" />
                        Resume Import
                    </button>
                @elseif($status === 'completed')
                    <div class="flex items-center text-green-600 dark:text-green-400">
                        <x-heroicon-s-check-circle class="w-6 h-6 mr-2" />
                        <span class="font-medium">Import Completed Successfully!</span>
                    </div>
                @elseif($status === 'failed')
                    <div class="flex items-center text-red-600 dark:text-red-400">
                        <x-heroicon-s-x-circle class="w-6 h-6 mr-2" />
                        <span class="font-medium">Import Failed</span>
                    </div>
                @endif

                @if(in_array($status, ['completed', 'failed']))
                    <a href="{{ route('extensions.importer.index') }}"
                       class="inline-flex items-center gap-2 rounded-xl bg-gray-200 px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-300 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700">
                        <x-heroicon-s-arrow-left class="w-5 h-5" />
                        Back to Importer
                    </a>
                @endif
            </div>

            @if($dryRunning)
                <div class="mt-4 flex items-center text-sm text-indigo-600 dark:text-indigo-300">
                    <x-heroicon-s-arrow-path class="h-4 w-4 mr-2 animate-spin" />
                    <span>Dry run in progress...</span>
                </div>
            @endif

            @if($status === 'processing')
            <div class="mt-4 flex items-center text-sm text-gray-600 dark:text-gray-400">
                <x-heroicon-s-arrow-path class="w-4 h-4 mr-2 animate-spin" />
                <span>Processing in progress... This page will auto-refresh.</span>
            </div>
            @endif
        </div>

        @if($dryRunCompleted)
        <div class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900">
            @php
                $dryImported = data_get($dryRunResults, 'imported', 0);
                $drySkipped = data_get($dryRunResults, 'skipped', 0);
                $dryErrors = data_get($dryRunResults, 'errors', []);
            @endphp
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Dry Run Summary</h3>
                <span class="inline-flex items-center gap-2 rounded-full bg-indigo-100 px-3 py-1 text-xs font-medium text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-100">
                    <x-heroicon-s-shield-check class="h-4 w-4" />
                    Validation complete
                </span>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div class="rounded-lg border border-gray-200 bg-white px-4 py-3 text-sm shadow-sm dark:border-gray-700 dark:bg-gray-800">
                    <p class="text-gray-500 dark:text-gray-300">Rows Checked</p>
                    <p class="text-xl font-semibold text-gray-900 dark:text-white">{{ number_format($dryImported + $drySkipped) }}</p>
                </div>
                <div class="rounded-lg border border-gray-200 bg-white px-4 py-3 text-sm shadow-sm dark:border-gray-700 dark:bg-gray-800">
                    <p class="text-gray-500 dark:text-gray-300">Valid Rows</p>
                    <p class="text-xl font-semibold text-emerald-600 dark:text-emerald-300">{{ number_format($dryImported) }}</p>
                </div>
                <div class="rounded-lg border border-gray-200 bg-white px-4 py-3 text-sm shadow-sm dark:border-gray-700 dark:bg-gray-800">
                    <p class="text-gray-500 dark:text-gray-300">Issues Found</p>
                    <p class="text-xl font-semibold text-red-600 dark:text-red-300">{{ number_format($drySkipped) }}</p>
                </div>
            </div>

            @if(!empty($dryErrors))
                <div class="mt-4 space-y-2 max-h-48 overflow-y-auto">
                    @foreach($dryErrors as $error)
                        <div class="rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm dark:border-red-700/80 dark:bg-red-700/80">
                            <p class="font-medium text-red-700 dark:text-white">Row {{ $error['row'] ?? 'Unknown' }}</p>
                            <p class="text-red-600 dark:text-red-100">{{ $error['error'] ?? 'Unknown error' }}</p>
                        </div>
                    @endforeach
                </div>
            @endif
        </div>
        @endif

        <!-- Errors -->
        @if(!empty($errors) && count($errors) > 0)
        <div class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900">
            <h3 class="text-lg font-semibold text-red-600 dark:text-red-400 mb-4">
                Import Errors ({{ count($errors) }})
            </h3>

            <div class="space-y-2 max-h-96 overflow-y-auto">
                @foreach(array_slice($errors, 0, 20) as $error)
                <div class="p-3 rounded border border-red-200 bg-red-50 dark:border-red-800 dark:bg-red-900/20">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <p class="text-sm font-medium text-red-800 dark:text-red-200">
                                Row {{ $error['row'] ?? 'Unknown' }}
                            </p>
                            <p class="text-sm text-red-700 dark:text-red-300 mt-1">
                                {{ $error['error'] ?? 'Unknown error' }}
                            </p>
                        </div>
                    </div>
                </div>
                @endforeach

                @if(count($errors) > 20)
                <p class="text-sm text-gray-600 dark:text-gray-400 text-center">
                    ... and {{ count($errors) - 20 }} more errors
                </p>
                @endif
            </div>
        </div>
        @endif

        <!-- Info -->
        <div class="rounded-xl border border-blue-200 bg-blue-50 p-4 shadow-sm dark:border-blue-800 dark:bg-blue-900/20">
            <div class="flex">
                <x-heroicon-s-information-circle class="h-5 w-5 mr-3 flex-shrink-0 text-blue-500 dark:text-white" />
                <div class="text-sm text-blue-800 dark:text-blue-200">
                    <p class="font-medium mb-1">Import Information:</p>
                    <ul class="list-disc list-inside space-y-1">
                        <li>The import will process {{ config('extensions.importer.chunk_size', 100) }} rows at a time</li>
                        <li>You can pause and resume the import at any time</li>
                        <li>Failed rows will be logged and can be reviewed after completion</li>
                        <li>Do not close this page while import is in progress</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    @endvolt
</div>
