<?php

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

use App\Extensions\Installed\Importer\Services\DatabaseImporter;
use App\Extensions\Installed\Importer\Services\DatabaseAdapters\DatabaseAdapterRegistry;
use Illuminate\Support\Str;
use Livewire\Component;
use Livewire\Attributes\Layout;

#[Layout('components.layouts.app', ['title' => 'Database Import', 'noPadding' => true])]
class Configure extends Component
{
    public $system;
    public $host = 'localhost';
    public $port = 3306;
    public $database = '';
    public $username = '';
    public $password = '';
    public $prefix = '';
    public $testSuccess = false;
    public $testError = null;
    public $adapterLabel;
    public $adapterPreview;
    public $systems = [];
    public $adapterMap = [];
    public $databasePlaceholder;
    public $prefixPlaceholder;
    public $placeholders = [];

    public function mount()
    {
        $this->systems = DatabaseAdapterRegistry::options();
        $systemKeys = implode(',', array_column($this->systems, 'id'));
        $defaultSystem = 'supportpal';

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

        foreach ($this->systems as $option) {
            $this->adapterMap[$option['id']] = $option;
        }

        $defaultAdapter = $this->adapterMap[$defaultSystem] ?? null;
        $this->adapterLabel = $defaultAdapter['label'] ?? Str::headline($defaultSystem);
        $this->adapterPreview = (bool) ($defaultAdapter['preview'] ?? false);

        $this->placeholders = [
            'blesta' => ['database' => 'blesta', 'prefix' => 'blesta_'],
            'whmcs' => ['database' => 'whmcs', 'prefix' => 'whmcs_'],
            'supportpal' => ['database' => 'supportpal', 'prefix' => 'sp_'],
        ];

        $defaultPlaceholders = $this->placeholders[$defaultSystem] ?? ['database' => 'database_name', 'prefix' => 'prefix_'];
        $this->databasePlaceholder = $defaultPlaceholders['database'];
        $this->prefixPlaceholder = $defaultPlaceholders['prefix'];
        $this->system = $defaultSystem;
    }

    protected function rules()
    {
        $systemKeys = implode(',', array_column($this->systems, 'id'));

        return [
            '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',
        ];
    }

    public function updatedSystem()
    {
        $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);

        $systemPlaceholders = $this->placeholders[$this->system] ?? ['database' => 'database_name', 'prefix' => 'prefix_'];
        $this->databasePlaceholder = $systemPlaceholders['database'];
        $this->prefixPlaceholder = $systemPlaceholders['prefix'];
    }

    public function testConnection()
    {
        $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,
            ]);

            $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();
        }
    }

    public function createImportJob()
    {
        $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 {
            $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' => $this->system,
            ]);

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

    public function render()
    {
        return view('extension.importer::database.configure', [
            'sources' => ['csv' => ['enabled' => true], 'database' => ['enabled' => true]],
        ]);
    }
}
