<?php

use App\Extensions\Installed\Importer\Models\ImportJob;
use App\Extensions\Installed\Importer\Services\DatabaseImporter;
use App\Extensions\Installed\Importer\Services\DatabaseAdapters\DatabaseAdapterRegistry;
use Illuminate\Support\Str;
use function Livewire\Volt\{state, rules};

$availableSystems = DatabaseAdapterRegistry::options();
$systemKeys = implode(',', array_column($availableSystems, 'id'));
$defaultSystem = 'supportpal';

foreach ($availableSystems as $option) {
    if (!($option['preview'] ?? false)) {
        $defaultSystem = $option['id'];
        break;
    }
}

$adapterMap = [];
foreach ($availableSystems as $option) {
    $adapterMap[$option['id']] = $option;
}
$defaultAdapter = $adapterMap[$defaultSystem] ?? null;
$defaultLabel = $defaultAdapter['label'] ?? Str::headline($defaultSystem);
$defaultPreview = (bool) ($defaultAdapter['preview'] ?? false);

$placeholders = [
    'supportpal' => [
        'database' => 'supportpal',
        'prefix' => 'sp_',
    ],
    'whmcs' => [
        'database' => 'whmcs',
        'prefix' => 'tbl',
    ],
    'blesta' => [
        'database' => 'blesta',
        'prefix' => '',
    ],
    'clientexec' => [
        'database' => 'clientexec',
        'prefix' => '',
    ],
];

state([
    'system' => $defaultSystem,
    'host' => 'localhost',
    'port' => 3306,
    'database' => '',
    'username' => '',
    'password' => '',
    'prefix' => '',
    'testSuccess' => false,
    'testError' => null,
    'adapterLabel' => $defaultLabel,
    'adapterPreview' => $defaultPreview,
    'systems' => $availableSystems,
    'adapterMap' => $adapterMap,
    'placeholders' => $placeholders,
    'databasePlaceholder' => $placeholders[$defaultSystem]['database'] ?? $defaultSystem,
    'prefixPlaceholder' => $placeholders[$defaultSystem]['prefix'] ?? '',
]);

rules([
    'system' => 'required|string|in:' . $systemKeys,
    'host' => 'required|string',
    'port' => 'required|integer|min:1|max:65535',
    'database' => 'required|string',
    'username' => 'required|string',
    'password' => 'nullable|string',
    'prefix' => 'nullable|string',
]);

$handleSystemChange = function () {
    $this->testSuccess = false;
    $this->testError = null;
    $current = $this->adapterMap[$this->system] ?? null;
    $this->adapterLabel = $current['label'] ?? Str::headline($this->system);
    $this->adapterPreview = (bool) ($current['preview'] ?? false);

    if ($this->system === 'whmcs' && empty($this->prefix)) {
        $this->prefix = 'tbl';
    }

    $defaults = $this->placeholders[$this->system] ?? null;
    if ($defaults) {
        $this->databasePlaceholder = $defaults['database'];
        $this->prefixPlaceholder = $defaults['prefix'];
    } else {
        $this->databasePlaceholder = $this->system;
        $this->prefixPlaceholder = '';
    }
};

$testConnection = function () {
    $this->validate();

    try {
        $adapterClass = DatabaseAdapterRegistry::adapterClass($this->system);
        if ($adapterClass && $adapterClass::isPreview()) {
            $this->adapterPreview = true;
            $this->testSuccess = false;
            $this->testError = 'This adapter is coming soon — database importing will be available in a future update.';
            session()->flash('error', sprintf('%s imports are coming soon.', $adapterClass::label()));
            return;
        }

        $adapter = DatabaseAdapterRegistry::resolve($this->system);
        $adapter->boot([
            'host' => $this->host,
            'port' => $this->port,
            'database' => $this->database,
            'username' => $this->username,
            'password' => $this->password,
            'prefix' => $this->prefix,
        ]);

        // Trigger a lightweight query to ensure connectivity
        $stages = $adapter->stages();
        if (!empty($stages)) {
            $adapter->count($stages[0]);
        }

        $this->testSuccess = true;
        $this->testError = null;
        $this->adapterPreview = false;
        $this->adapterLabel = $adapterClass ? $adapterClass::label() : Str::headline($this->system);
        session()->flash('message', sprintf('%s connection successful!', $adapter::label()));
    } catch (\Throwable $e) {
        $this->testSuccess = false;
        $this->testError = 'Connection failed: ' . $e->getMessage();
    }
};

$createImportJob = function () {
    $this->validate();

    $adapterClass = DatabaseAdapterRegistry::adapterClass($this->system);
    if ($adapterClass && $adapterClass::isPreview()) {
        $this->adapterPreview = true;
        session()->flash('error', sprintf('%s imports are coming soon and cannot be started yet.', $adapterClass::label()));
        return;
    }

    if (!$this->testSuccess) {
        session()->flash('error', 'Please test the connection first.');
        return;
    }

    try {
        $system = $this->system;

        $job = DatabaseImporter::createJob([
            'host' => $this->host,
            'port' => $this->port,
            'database' => $this->database,
            'username' => $this->username,
            'password' => $this->password,
            'prefix' => $this->prefix,
        ], [
            'prefix' => $this->prefix,
            'database_system' => $system,
        ]);

        return redirect()->route('extensions.importer.database.process', $job);
    } catch (\Exception $e) {
        session()->flash('error', 'Failed to create import job: ' . $e->getMessage());
    }
};

?>

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

    @volt('extensions.importer.database.configure')
    <div class="space-y-6">
        <!-- Breadcrumb -->
        <nav class="flex" 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="text-gray-700 hover:text-blue-600 dark:text-gray-300">
                        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">Database Configuration</span>
                    </div>
                </li>
            </ol>
        </nav>

        @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 px-4 py-3 rounded">
                {{ session('error') }}
            </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 px-4 py-3 rounded">
                {{ session('message') }}
            </div>
        @endif

        <!-- Configuration Form -->
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Database Connection Settings</h2>
            <p class="text-gray-600 dark:text-gray-400 mb-6">
                @php
                    $currentAdapter = $this->adapterMap[$system] ?? null;
                @endphp
                Choose your source system and provide the database credentials for {{ $adapterLabel }}.
            </p>

            <form wire:submit="testConnection" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- System -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Source System *
                        </label>
                        <select wire:model="system"
                                wire:change="handleSystemChange"
                                class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            @foreach($this->systems as $adapter)
                                <option value="{{ $adapter['id'] }}"
                                        @disabled($adapter['preview'] ?? false)>
                                    {{ $adapter['label'] }}{{ ($adapter['preview'] ?? false) ? ' (Coming Soon)' : '' }}
                                </option>
                            @endforeach
                        </select>
                        @if($adapterPreview)
                            <p class="text-sm text-amber-600 dark:text-amber-300 mt-2">
                                This adapter is in preview and cannot run imports yet.
                            </p>
                        @endif
                        @error('system') <span class="text-sm text-red-600 dark:text-red-400 mt-1">{{ $message }}</span> @enderror
                    </div>

                    <!-- Host -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Database Host *
                        </label>
                        <input type="text"
                               wire:model="host"
                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               placeholder="localhost">
                        @error('host') <span class="text-sm text-red-600 dark:text-red-400 mt-1">{{ $message }}</span> @enderror
                    </div>

                    <!-- Port -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Database Port *
                        </label>
                        <input type="number"
                               wire:model="port"
                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               placeholder="3306">
                        @error('port') <span class="text-sm text-red-600 dark:text-red-400 mt-1">{{ $message }}</span> @enderror
                    </div>

                    <!-- Database Name -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Database Name *
                        </label>
                        <input type="text"
                               wire:model="database"
                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               placeholder="{{ $databasePlaceholder }}">
                        @error('database') <span class="text-sm text-red-600 dark:text-red-400 mt-1">{{ $message }}</span> @enderror
                    </div>

                    <!-- Table Prefix -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Table Prefix
                        </label>
                        <input type="text"
                               wire:model="prefix"
                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               placeholder="{{ $prefixPlaceholder }}">
                        @error('prefix') <span class="text-sm text-red-600 dark:text-red-400 mt-1">{{ $message }}</span> @enderror
                    </div>

                    <!-- Username -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Database Username *
                        </label>
                        <input type="text"
                               wire:model="username"
                               autocomplete="off"
                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               placeholder="root">
                        @error('username') <span class="text-sm text-red-600 dark:text-red-400 mt-1">{{ $message }}</span> @enderror
                    </div>

                    <!-- Password -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Database Password
                        </label>
                        <input type="password"
                               wire:model="password"
                               autocomplete="new-password"
                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               placeholder="••••••••">
                        @error('password') <span class="text-sm text-red-600 dark:text-red-400 mt-1">{{ $message }}</span> @enderror
                    </div>
                </div>

                <!-- Connection Status -->
                @if($testSuccess)
                <div class="p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
                    <div class="flex items-center text-green-800 dark:text-green-200">
                        <x-heroicon-s-check-circle class="h-5 w-5 mr-2" />
                        <span class="font-medium">Connection Successful!</span>
                    </div>
                </div>
                @endif

                @if($testError)
                <div class="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
                    <div class="flex items-start text-red-800 dark:text-red-200">
                        <x-heroicon-s-x-circle class="h-5 w-5 mr-2 flex-shrink-0 mt-0.5" />
                        <div>
                            <span class="font-medium">Connection Failed</span>
                            <p class="text-sm mt-1">{{ $testError }}</p>
                        </div>
                    </div>
                </div>
                @endif

                <!-- Test Connection Button -->
                <div class="flex justify-end">
                    <button type="submit"
                            @disabled($adapterPreview)
                            class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-medium rounded-lg">
                        <x-heroicon-s-signal class="w-5 h-5 mr-2" />
                        @if($adapterPreview)
                            Coming Soon
                        @else
                            Test Connection
                        @endif
                    </button>
                </div>
            </form>
        </div>

        <!-- Start Import -->
        @if($testSuccess && !$adapterPreview)
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Ready to Import</h3>
            <p class="text-gray-600 dark:text-gray-400 mb-4">
                The connection test was successful. Click the button below to start importing data from {{ $adapterLabel }}.
            </p>

            <button wire:click="createImportJob"
                    class="inline-flex items-center px-6 py-3 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg">
                <x-heroicon-s-play class="w-5 h-5 mr-2" />
                Start Database Import
            </button>
        </div>
        @endif

        <!-- Warning -->
        <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
            <div class="flex">
                <x-heroicon-s-exclamation-triangle class="h-5 w-5 text-yellow-400 mr-3 flex-shrink-0" />
                <div class="text-sm text-yellow-800 dark:text-yellow-200 space-y-1">
                    <p class="font-medium">Important Notes:</p>
                    <p>Ensure you have a backup of your Ticaga database before importing.</p>
                    <p>The source database will not be modified (read-only access).</p>
                    <p>Large databases may take significant time to import.</p>
                    <p>Users will be created with a default password and forced to reset on first login.</p>
                </div>
            </div>
        </div>
    </div>
    @endvolt
</div>
