<?php

namespace App\Livewire\Admin\Plans\Modals;

use App\Models\Plan;
use App\Models\FeatureGroup;
use Illuminate\Support\Str;
use LivewireUI\Modal\ModalComponent;

class Form extends ModalComponent
{
    public $planId;
    public $ai_config;

    public $name = '';
    public $price = 0;

    public $credit_limit = 0;
    public $device_limit = 1;

    public $yearly_discount_months = 0;

    public $active = true;
    public $is_featured = false;

    public $step = 1;

    // 🔥 GROUPED FEATURES
    public $groupedFeatures = [];

    // 🔥 SELECTED IDS
    public $selectedFeatures = [];

    protected $listeners = [
        'featureCreated' => 'reloadFeatures',
    ];

    public function mount($id = null)
    {
        // 🔥 GROUPS + FEATURES LADEN
        $this->groupedFeatures = FeatureGroup::with([
            'features' => fn ($q) => $q->where('active', true)->orderBy('sort')
        ])
            ->orderBy('sort')
            ->get();

        if ($id) {
            $plan = Plan::with('features')->findOrFail($id);

            $this->planId = $plan->id;
            $this->ai_config = $plan->ai_config ?? [];
            $this->name = $plan->name;
            $this->price = $plan->price;

            $this->credit_limit = $plan->credit_limit;
            $this->device_limit = $plan->device_limit;

            $this->yearly_discount_months = $plan->yearly_discount_months ?? 0;

            // 🔥 WICHTIG: KEIN ? mehr
            $this->selectedFeatures = $plan->features
                ? $plan->features->pluck('id')->toArray()
                : [];

            $this->active = $plan->active;
            $this->is_featured = $plan->is_featured;
        }
    }

    public function reloadFeatures($featureId = null)
    {
        $this->groupedFeatures = \App\Models\FeatureGroup::with([
            'features' => fn ($q) => $q->where('active', true)->orderBy('sort')
        ])
            ->orderBy('sort')
            ->get();

        // 👉 optional direkt auswählen
        if ($featureId) {
            $this->selectedFeatures[] = $featureId;
        }
    }

    public function toggleFeature($id)
    {
        if (in_array($id, $this->selectedFeatures)) {
            $this->selectedFeatures = array_values(
                array_diff($this->selectedFeatures, [$id])
            );
        } else {
            $this->selectedFeatures[] = $id;
        }
    }

    public function nextStep()
    {
        $this->validateStep1();
        $this->step = 2;
    }

    public function prevStep()
    {
        $this->step = 1;
    }

    public function updated($field)
    {
        if (in_array($field, ['price', 'credit_limit', 'device_limit', 'yearly_discount_months'])) {
            if ($this->$field < 0) {
                $this->$field = 0;
            }
        }

        if ($field === 'yearly_discount_months' && $this->yearly_discount_months > 12) {
            $this->yearly_discount_months = 12;
        }

        if ($field === 'price' && $this->price == 0) {
            $this->yearly_discount_months = 0;
        }
    }

    protected function validateStep1()
    {
        $this->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|integer|min:0',
            'credit_limit' => 'required|integer|min:0',
            'device_limit' => 'required|integer|min:0',
            'yearly_discount_months' => 'nullable|integer|min:0|max:12',
        ]);
    }


    public function getAiModelDefaults(): array
    {
        $model = $this->ai_config['model'] ?? null;

        if (!$model) return [];

        return config('ai_models.' . $model) ?? [];
    }

    public function save()
    {
        // 🔥 AI CONFIG sauber aufbauen (Defaults + Overrides)
        $modelKey = $this->ai_config['model'] ?? null;

        $finalAiConfig = [];

        if ($modelKey) {
            $defaults = config('ai_models.' . $modelKey) ?? [];

            // 👉 nur relevante Felder übernehmen
            $finalAiConfig = [
                'model_key' => $modelKey,
                'model' => $defaults['model'] ?? null,
                'max_tokens' => $this->ai_config['max_tokens'] ?? $defaults['max_tokens'] ?? null,
                'temperature' => $this->ai_config['temperature'] ?? $defaults['temperature'] ?? null,
            ];
        }

        $this->validateStep1();

        $plan = Plan::updateOrCreate(
            ['id' => $this->planId],
            [
                'name' => $this->name,
                'plan_key' => Str::slug($this->name),
                'price' => $this->price,
                'credit_limit' => $this->credit_limit,
                'device_limit' => $this->device_limit,
                'yearly_discount_months' => $this->price > 0 ? $this->yearly_discount_months : 0,
                'active' => $this->active,
                'is_featured' => $this->is_featured,
                'ai_config' => $finalAiConfig,
            ]
        );

        // 🔥 PIVOT SYNC
        $plan->features()->sync($this->selectedFeatures);

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

    public function render()
    {
        return view('livewire.admin.plans.modals.form');
    }
}
