<?php

namespace App\Components;

use App\Services\HistoryService;
use Illuminate\Database\Eloquent\Model;
use Livewire\Component;

class MetaManager extends Component {
    public Model $owner;

    public $newKey = '';
    public $newValue = '';
    public $search = '';
    public $isEditing = null;
    public $editingValue = '';

    protected $rules = [
        'newKey' => 'required|string|max:255',
        'newValue' => 'required',
    ];

    public function addMeta(HistoryService $history) {
        $this->validate();

        $exists = $this->owner->getMeta($this->newKey);

        $this->owner->setMeta($this->newKey, $this->newValue);

        $action = $exists ? "Updated metadata key" : "Added metadata key";
        $history->add($this->owner, "{$action}: {$this->newKey}", [
            'key' => $this->newKey,
            'value' => $this->newValue
        ]);

        $this->reset(['newKey', 'newValue']);
        $this->dispatch('notify', ['type' => 'success', 'message' => 'Meta added successfully!']);
    }

    public function removeMeta(HistoryService $history, $key) {
        $this->owner->deleteMeta($key);

        $history->add($this->owner, "Removed metadata key: {$key}", ['key' => $key]);

        $this->dispatch('notify', ['type' => 'info', 'message' => "Key '{$key}' removed."]);
    }

    public function startEditing($key) {
        $this->isEditing = $key;
        $this->editingValue = $this->owner->getMeta($key);
    }

    public function saveEdit(HistoryService $history, $key) {
        $this->owner->setMeta($key, $this->editingValue);

        $history->add($this->owner, "Updated metadata value for: {$key}", [
            'key' => $key,
            'new_value' => $this->editingValue
        ]);

        $this->isEditing = null;
        $this->dispatch('notify', ['type' => 'success', 'message' => 'Value updated.']);
    }

    public function cancelEdit() {
        $this->isEditing = null;
    }

    public function clearAll(HistoryService $history) {
        $count = count($this->owner->getAllMeta());

        foreach ($this->owner->getAllMeta() as $key => $value) {
            $this->owner->deleteMeta($key);
        }

        $history->add($this->owner, "Cleared all metadata ({$count} entries).");

        $this->dispatch('notify', ['type' => 'danger', 'message' => 'All metadata cleared.']);
    }

    public function render() {
        $allMeta = collect($this->owner->getAllMeta());

        if ($this->search) {
            $allMeta = $allMeta->filter(function ($value, $key) {
                return str_contains(strtolower($key), strtolower($this->search)) ||
                    str_contains(strtolower($value), strtolower($this->search));
            });
        }

        return view('components.meta-manager', [
            'meta' => $allMeta
        ]);
    }
}