<?php

namespace App\Livewire;

use App\Models\Plan;
use App\Models\PlanFeature;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class AdminPlansPage extends Component
{
    public ?int $selectedPlanId = null;

    public array $planDraft = [
        'name' => '',
        'slug' => '',
        'interval' => 'monthly',
        'is_active' => true,
    ];

    public array $featuresDraft = [];

    public function mount(): void
    {
        $first = Plan::query()->orderBy('id')->first();
        if ($first !== null) {
            $this->selectPlan($first->id);
        }
    }

    public function selectPlan(int $planId): void
    {
        $plan = Plan::query()->with('features')->find($planId);
        if ($plan === null) {
            return;
        }

        $this->selectedPlanId = $plan->id;
        $this->planDraft = [
            'name' => (string) $plan->name,
            'slug' => (string) $plan->slug,
            'interval' => (string) $plan->interval,
            'is_active' => (bool) $plan->is_active,
        ];
        $this->featuresDraft = $plan->features
            ->map(fn (PlanFeature $feature): array => [
                'feature_key' => (string) $feature->feature_key,
                'limit' => $feature->limit,
            ])->values()->all();
    }

    public function addFeatureRow(): void
    {
        $this->featuresDraft[] = ['feature_key' => '', 'limit' => null];
    }

    public function removeFeatureRow(int $idx): void
    {
        unset($this->featuresDraft[$idx]);
        $this->featuresDraft = array_values($this->featuresDraft);
    }

    public function savePlan(): void
    {
        if ($this->selectedPlanId === null) {
            return;
        }

        $validated = $this->validate([
            'planDraft.name' => ['required', 'string', 'max:255'],
            'planDraft.slug' => ['required', 'string', 'max:255'],
            'planDraft.interval' => ['required', 'string', 'max:32'],
            'planDraft.is_active' => ['boolean'],
            'featuresDraft.*.feature_key' => ['nullable', 'string', 'max:255'],
            'featuresDraft.*.limit' => ['nullable', 'integer', 'min:0'],
        ]);

        $plan = Plan::query()->find($this->selectedPlanId);
        if ($plan === null) {
            return;
        }

        $plan->update($validated['planDraft']);

        $plan->features()->delete();
        foreach (($validated['featuresDraft'] ?? []) as $feature) {
            if (trim((string) ($feature['feature_key'] ?? '')) === '') {
                continue;
            }
            $plan->features()->create([
                'feature_key' => (string) $feature['feature_key'],
                'limit' => $feature['limit'],
            ]);
        }

        session()->flash('toast', (string) __('budgets.admin_console.plans_saved'));
    }

    public function render()
    {
        return view('livewire.admin-plans-page', [
            'plans' => Plan::query()->orderBy('price_cents')->get(),
        ])->title((string) __('budgets.admin_console.plans_title'));
    }
}
