<?php

namespace App\Livewire\Modals;

use App\Domains\Bio\Models\BioPage;
use App\Domains\Workspace\Models\Workspace;
use App\Livewire\Pages\Bio\Index;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

class EditBioPage extends ModalComponent
{
    public int $workspaceId = 0;

    public string $bioUlid = '';

    public string $title = '';

    public string $slug = '';

    public bool $isPublished = false;

    public string $theme = 'dark';

    public function mount(string $bioUlid): void
    {
        $bio = BioPage::where('ulid', $bioUlid)->firstOrFail();

        $this->authorizeWorkspace($bio->workspace_id);

        $this->workspaceId = $bio->workspace_id;
        $this->bioUlid = $bioUlid;
        $this->title = $bio->getTranslation('title', 'en') ?? '';
        $this->slug = $bio->slug;
        $this->isPublished = $bio->is_published;
        $this->theme = is_array($bio->theme) ? ($bio->theme['preset'] ?? 'dark') : 'dark';
    }

    /** @return array<string, string> */
    protected function rules(): array
    {
        return [
            'title' => 'required|max:200',
            'slug' => 'nullable|alpha_dash|max:80',
            'isPublished' => 'boolean',
            'theme' => 'in:dark,light,purple,blue',
        ];
    }

    public function save(): void
    {
        $this->validate();

        $bio = BioPage::where('ulid', $this->bioUlid)
            ->where('workspace_id', $this->workspaceId)
            ->firstOrFail();

        $bio->update([
            'title' => ['en' => $this->title, 'de' => $this->title],
            'slug' => $this->slug ?: $bio->slug,
            'is_published' => $this->isPublished,
            'theme' => ['preset' => $this->theme],
        ]);

        $this->dispatch('bio-updated')->to(Index::class);
        $this->dispatch('toast', message: 'Bio Page aktualisiert', type: 'success');
        $this->closeModal();
    }

    public static function modalMaxWidth(): string
    {
        return 'md';
    }

    public function render(): View
    {
        return view('livewire.modals.edit-bio-page');
    }

    private function authorizeWorkspace(int $workspaceId): void
    {
        Workspace::where('id', $workspaceId)
            ->where(fn ($q) => $q
                ->where('owner_id', auth()->id())
                ->orWhereHas('members', fn ($q) => $q->where('user_id', auth()->id()))
            )->firstOrFail();
    }
}
