<?php

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

use App\Extensions\Installed\Importer\Services\ApiImporter;
use App\Extensions\Installed\Importer\Services\ApiAdapters\ApiAdapterRegistry;
use Livewire\Component;
use Livewire\Attributes\Layout;

#[Layout('components.layouts.app', ['title' => 'API Import', 'noPadding' => true])]
class Configure extends Component
{
    public $system;
    public $base_url = '';
    public $subdomain = '';
    public $api_key = '';
    public $username = '';
    public $token = '';
    public $testSuccess = false;
    public $testError = null;
    public $adapterLabel;
    public $adapterPreview;
    public $systems = [];
    public $adapterMap = [];
    public $baseUrlPlaceholder;
    public $apiPlaceholders = [];
    public $fieldRequirements = [];
    public $requiredFields = [];

    public function mount()
    {
        $this->systems = ApiAdapterRegistry::options();
        $defaultSystem = $this->systems[0]['id'] ?? 'freshdesk';

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

        $this->adapterLabel = $this->adapterMap[$defaultSystem]['label'] ?? 'API';
        $this->adapterPreview = (bool) ($this->adapterMap[$defaultSystem]['preview'] ?? false);

        $this->apiPlaceholders = [
            'freshdesk' => 'https://yourdomain.freshdesk.com',
            'zendesk' => 'https://yourcompany.zendesk.com',
            'helpscout' => 'https://api.helpscout.net',
        ];

        $this->fieldRequirements = [
            'freshdesk' => [
                'base_url' => true,
                'subdomain' => false,
                'api_key' => true,
                'username' => false,
                'token' => false,
            ],
            'zendesk' => [
                'base_url' => true,
                'subdomain' => false,
                'api_key' => true,
                'username' => true,
                'token' => true,
            ],
            'helpscout' => [
                'base_url' => false,
                'subdomain' => false,
                'api_key' => true,
                'username' => false,
                'token' => true,
            ],
        ];

        $this->baseUrlPlaceholder = $this->apiPlaceholders[$defaultSystem] ?? 'https://yourdomain.example.com';
        $this->requiredFields = $this->fieldRequirements[$defaultSystem] ?? [
            'base_url' => true,
            'subdomain' => false,
            'api_key' => true,
            'username' => false,
            'token' => false,
        ];

        $this->system = $defaultSystem;
    }

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

        return [
            'system' => 'required|string|in:' . $systemKeys,
            'base_url' => 'nullable|string',
            'subdomain' => 'nullable|string',
            'api_key' => 'required|string',
            'username' => 'nullable|string',
            'token' => 'nullable|string',
        ];
    }

    public function updatedSystem()
    {
        $this->testSuccess = false;
        $this->testError = null;
        $current = $this->adapterMap[$this->system] ?? null;
        $this->adapterLabel = $current['label'] ?? 'API';
        $this->adapterPreview = (bool) ($current['preview'] ?? false);

        $this->baseUrlPlaceholder = $this->apiPlaceholders[$this->system] ?? 'https://yourdomain.example.com';

        $this->requiredFields = $this->fieldRequirements[$this->system] ?? [
            'base_url' => true,
            'subdomain' => false,
            'api_key' => true,
            'username' => false,
            'token' => false,
        ];
    }

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

        if ($this->adapterPreview) {
            session()->flash('error', "{$this->adapterLabel} API adapter is coming soon.");
            return;
        }

        try {
            $apiConfig = [
                'base_url' => $this->base_url,
                'subdomain' => $this->subdomain,
                'api_key' => $this->api_key,
                'username' => $this->username,
                'token' => $this->token,
            ];

            $class = ApiAdapterRegistry::adapterClass($this->system);
            if (!$class) {
                throw new \RuntimeException("Unknown API adapter: {$this->system}");
            }

            $adapter = app($class);
            $adapter->boot($apiConfig, ['api_system' => $this->system]);

            $this->testSuccess = true;
            $this->testError = null;
            session()->flash('message', "{$this->adapterLabel} API configuration is valid.");
        } catch (\Throwable $e) {
            $this->testSuccess = false;
            $this->testError = 'Validation failed: ' . $e->getMessage();
        }
    }

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

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

        try {
            $job = ApiImporter::createJob(
                [
                    'base_url' => $this->base_url,
                    'subdomain' => $this->subdomain,
                    'api_key' => $this->api_key,
                    'username' => $this->username,
                    'token' => $this->token,
                ],
                [
                    'api_system' => $this->system,
                ]
            );

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

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