<?php

namespace App\Livewire\Admin;

use App\Models\AppBuilder;
use App\Models\SystemSetting;
use App\Services\PluginManager;
use Illuminate\Support\Str;
use Livewire\Attributes\On;
use Livewire\Component;

class BuilderForm extends Component
{
    public $showModal = false;

    public $builderId = null;

    public $name = '';

    public $url = '';

    public $port = 8080;

    public $server_key = '';

    public $max_queue = 5;

    public $platforms = [];

    public $status = 'active';

    public $credit_cost = 1;

    public $isEdit = false;

    public $isDefault = false;

    public $purchaseCodeMissing = false;

    protected function rules()
    {
        $rules = [
            'name' => 'required|string|max:255',
            'max_queue' => 'required|integer|min:1|max:100',
            'platforms' => 'required|array|min:1',
            'platforms.*' => 'required|string|max:50',
            'status' => 'required|in:active,inactive',
            'credit_cost' => 'required|integer|min:1|max:100',
        ];

        // For default builder, URL/port/server_key are locked and don't need validation
        if (! $this->isDefault) {
            $rules['url'] = 'required|url|max:255';
            $rules['port'] = 'required|integer|min:1|max:65535';
            $rules['server_key'] = 'required|string|max:255';

            if ($this->isEdit) {
                $rules['server_key'] .= '|unique:app_builders,server_key,'.$this->builderId;
            } else {
                $rules['server_key'] .= '|unique:app_builders,server_key';
            }
        }

        return $rules;
    }

    public function generateServerKey()
    {
        if (config('app.demo')) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('common.demo_mode_action_disabled')
            );

            return;
        }

        $this->server_key = Str::random(32);
    }

    #[On('edit-builder')]
    public function edit($id)
    {
        $this->resetForm();
        $builder = AppBuilder::findOrFail($id);

        $this->builderId = $builder->id;
        $this->name = $builder->name;
        $this->isDefault = $builder->is_default;

        if ($this->isDefault) {
            // Use locked values for default builder
            $this->url = AppBuilder::DEFAULT_BUILDER_URL;
            $this->port = AppBuilder::DEFAULT_BUILDER_PORT;

            // In demo mode, show empty server_key and hide warning
            if (config('app.demo')) {
                $this->server_key = '';
                $this->purchaseCodeMissing = false;
            } else {
                $this->server_key = SystemSetting::get('purchase_code', '');
                $this->purchaseCodeMissing = empty($this->server_key);
            }
        } else {
            $this->url = $builder->url;
            $this->port = $builder->port;
            $this->server_key = $builder->getOriginal('server_key');
            $this->purchaseCodeMissing = false;

            // Clear sensitive fields in demo mode for non-default builders
            if (config('app.demo')) {
                $this->server_key = '';
            }
        }

        $this->max_queue = $builder->max_queue;
        $this->platforms = $builder->platforms ?? [];
        $this->status = $builder->status;
        $this->credit_cost = $builder->credit_cost ?? 1;
        $this->isEdit = true;

        $this->showModal = true;
    }

    #[On('create-builder')]
    public function create()
    {
        $this->resetForm();
        $this->generateServerKey();
        $this->showModal = true;
    }

    public function save()
    {
        if (config('app.demo')) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('common.demo_mode_modify_disabled')
            );

            return;
        }

        $this->validate();

        if ($this->isEdit) {
            $builder = AppBuilder::findOrFail($this->builderId);

            // Build update data - editable fields for all builders
            $updateData = [
                'name' => $this->name,
                'max_queue' => $this->max_queue,
                'platforms' => $this->platforms,
                'status' => $this->status,
                'credit_cost' => $this->credit_cost,
            ];

            // Only allow URL, port, and server_key updates for non-default builders
            if (! $builder->is_default) {
                $updateData['url'] = $this->url;
                $updateData['port'] = $this->port;
                $updateData['server_key'] = $this->server_key;
            }

            $builder->update($updateData);

            $this->dispatch('show-toast',
                type: 'success',
                message: __('common.item_updated', ['item' => 'Builder'])
            );
        } else {
            // Creating new builder - always non-default
            AppBuilder::create([
                'name' => $this->name,
                'url' => $this->url,
                'port' => $this->port,
                'server_key' => $this->server_key,
                'max_queue' => $this->max_queue,
                'platforms' => $this->platforms,
                'status' => $this->status,
                'credit_cost' => $this->credit_cost,
                'is_default' => false,
            ]);

            $this->dispatch('show-toast',
                type: 'success',
                message: __('common.item_created', ['item' => 'Builder'])
            );
        }

        $this->dispatch('builderUpdated');
        $this->closeModal();
    }

    public function closeModal()
    {
        $this->showModal = false;
        $this->isDefault = false;
        $this->purchaseCodeMissing = false;
        $this->resetValidation();
    }

    private function resetForm()
    {
        $this->builderId = null;
        $this->name = '';
        $this->url = '';
        $this->port = 8080;
        $this->server_key = '';
        $this->max_queue = 5;
        $this->platforms = [];
        $this->status = 'active';
        $this->credit_cost = 1;
        $this->isEdit = false;
        $this->isDefault = false;
        $this->purchaseCodeMissing = false;
        $this->resetValidation();
    }

    /**
     * Get available platform plugins.
     */
    public function getAvailablePlatformsProperty()
    {
        $pluginManager = app(PluginManager::class);

        return $pluginManager->getActivePlatforms()
            ->map(function ($platform) {
                return [
                    'id' => $platform->getPlatformId(),
                    'name' => $platform->getName(),
                ];
            });
    }

    public function render()
    {
        return view('livewire.admin.builder-form');
    }
}
