<?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\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

class CreateBioPage extends ModalComponent
{
    public string $workspaceUlid = '';

    public int $workspaceId = 0;

    public string $title = '';

    public string $slug = '';

    /** @return array<string, mixed> */
    protected function rules(): array
    {
        $wsId = $this->workspaceId;
        if (! $wsId) {
            $ws = current_workspace();
            $wsId = $ws !== null ? $ws->id : 0;
        }

        return [
            'title' => 'required|max:200',
            'slug' => [
                'nullable', 'alpha_dash', 'max:80',
                Rule::unique('bio_pages', 'slug')
                    ->where('workspace_id', $wsId)
                    ->whereNull('domain_id')
                    ->whereNull('deleted_at'),
            ],
        ];
    }

    public function mount(string $workspaceUlid = ''): void
    {
        if ($workspaceUlid) {
            $workspace = Workspace::where('ulid', $workspaceUlid)->firstOrFail();
            abort_unless(
                $workspace->owner_id === auth()->id() ||
                $workspace->members()->where('user_id', auth()->id())->exists(),
                404
            );
            $this->workspaceUlid = $workspaceUlid;
            $this->workspaceId = $workspace->id;
        }
    }

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

        $wsId = $this->workspaceId ?: require_workspace()->id;

        if (empty($this->slug)) {
            $this->slug = Str::slug($this->title).'-'.Str::random(4);
        }

        BioPage::create([
            'workspace_id' => $wsId,
            'slug' => $this->slug,
            'title' => ['en' => $this->title, 'de' => $this->title],
            'theme' => [],
            'is_published' => false,
        ]);

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

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

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