<?php

namespace App\Livewire\Notes;

use App\Models\Activity;
use App\Models\Note;
use Livewire\Component;

class Index extends Component
{
    public string $search      = '';
    public string $filterColor = '';

    // Formular
    public bool    $showForm = false;
    public ?string $editId   = null;
    public string  $title    = '';
    public string  $content  = '';
    public string  $color    = 'yellow';

    public function updatedSearch(): void { /* live search, kein reset nötig */ }

    // ── Erstellen / Bearbeiten ────────────────────────────────────────────

    public function openCreate(): void
    {
        $this->reset(['editId', 'title', 'content']);
        $this->color    = 'yellow';
        $this->showForm = true;
    }

    public function openEdit(string $id): void
    {
        $note = Note::forUser(auth()->id())->findOrFail($id);

        $this->editId  = $id;
        $this->title   = $note->title ?? '';
        $this->content = $note->content;
        $this->color   = $note->color;
        $this->showForm = true;
    }

    public function save(): void
    {
        $this->validate([
            'content' => ['required', 'string', 'max:5000'],
            'title'   => ['nullable', 'string', 'max:255'],
            'color'   => ['required', 'in:' . implode(',', Note::COLORS)],
        ]);

        if ($this->editId) {
            Note::forUser(auth()->id())->where('id', $this->editId)->update([
                'title'   => $this->title ?: null,
                'content' => $this->content,
                'color'   => $this->color,
            ]);
        } else {
            Note::create([
                'user_id' => auth()->id(),
                'title'   => $this->title ?: null,
                'content' => $this->content,
                'color'   => $this->color,
            ]);

            Activity::log(
                auth()->id(),
                Activity::TYPE_NOTE_CREATED,
                Activity::localizedTitle('note_created', auth()->user()->locale ?? 'de'),
                $this->title ?: null,
            );
        }

        $this->closeForm();
        $this->dispatch('notify', ['type' => 'success', 'message' => $this->editId ? 'Notiz gespeichert' : 'Notiz erstellt']);
    }

    public function closeForm(): void
    {
        $this->reset(['showForm', 'editId', 'title', 'content']);
        $this->color = 'yellow';
    }

    // ── Pin / Löschen ─────────────────────────────────────────────────────

    public function togglePin(string $id): void
    {
        $note = Note::forUser(auth()->id())->findOrFail($id);
        $note->update(['pinned' => !$note->pinned]);
    }

    public function delete(string $id): void
    {
        Note::forUser(auth()->id())->where('id', $id)->delete();

        Activity::log(auth()->id(), Activity::TYPE_NOTE_DELETED, Activity::localizedTitle('note_deleted', auth()->user()->locale ?? 'de'));
    }

    // ── Render ────────────────────────────────────────────────────────────

    public function render()
    {
        $userId = auth()->id();

        $query = Note::forUser($userId)->orderByDesc('pinned')->orderByDesc('created_at');

        if ($this->search !== '') {
            $query->search($this->search);
        }

        if ($this->filterColor !== '') {
            $query->where('color', $this->filterColor);
        }

        $notes = $query->get();

        $stats = [
            'total'  => Note::forUser($userId)->count(),
            'pinned' => Note::forUser($userId)->where('pinned', true)->count(),
        ];

        return view('livewire.notes.index', [
            'notes' => $notes,
            'stats' => $stats,
        ])->layout('layouts.app');
    }
}
