<?php

namespace App\Livewire\Modals;

use App\Domains\Ai\Services\SlugSuggester;
use App\Domains\Link\Models\Link;
use App\Domains\Workspace\Models\Workspace;
use App\Livewire\Pages\Links\Index;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Livewire\Attributes\Validate;
use LivewireUI\Modal\ModalComponent;

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

    public int $workspaceId = 0;

    #[Validate('required|url|max:2048')]
    public string $targetUrl = '';

    #[Validate('nullable|alpha_dash|min:3|max:64')]
    public string $slug = '';

    #[Validate('nullable|string|max:200')]
    public string $title = '';

    public bool $autoSlug = true;

    /** @var string[] */
    public array $slugSuggestions = [];

    public bool $aiLoading = false;

    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 updatedTargetUrl(string $value): void
    {
        if ($this->autoSlug && $value) {
            $this->slug = Str::random(6);
        }
    }

    public function updatedSlug(): void
    {
        $this->autoSlug = false;
    }

    public function regenerateSlug(): void
    {
        $this->slug = Str::random(6);
        $this->autoSlug = true;
    }

    public function generateSlug(): void
    {
        if (empty($this->slug)) {
            $this->slug = Str::random(6);
        }
    }

    public function suggestSlugs(): void
    {
        if (! filter_var($this->targetUrl, FILTER_VALIDATE_URL)) {
            $this->dispatch('toast', message: 'Bitte zuerst eine gültige URL eingeben', type: 'warning');

            return;
        }
        $this->aiLoading = true;
        try {
            $this->slugSuggestions = app(SlugSuggester::class)->suggest($this->targetUrl);
        } catch (\Exception $e) {
            $this->dispatch('toast', message: 'AI-Fehler: '.$e->getMessage(), type: 'error');
        } finally {
            $this->aiLoading = false;
        }
    }

    public function pickSuggestion(string $slug): void
    {
        $this->slug = $slug;
        $this->autoSlug = false;
        $this->slugSuggestions = [];
    }

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

        $wsId = $this->workspaceId;
        if (! $wsId) {
            $ws = current_workspace();
            if (! $ws) {
                $this->addError('targetUrl', 'Workspace nicht gefunden.');

                return;
            }
            $wsId = $ws->id;
        }

        $slug = $this->slug ?: Str::random(6);

        $link = Link::create([
            'workspace_id' => $wsId,
            'target_url' => $this->targetUrl,
            'slug' => $slug,
            'title' => $this->title ?: null,
            'status' => 'active',
            'created_by' => auth()->id(),
        ]);

        $this->dispatch('link-created', linkId: $link->ulid)->to(Index::class);
        $this->dispatch('toast', message: 'Link erstellt', type: 'success');
        $this->closeModal();
    }

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