<?php

namespace Daylight\Core\Modules\Admin\Entities;

use Daylight\Core\Modules\Admin\Entities\Contracts\NavigationItem;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class Page implements NavigationItem
{
    public string $label;

    protected bool $translateLabel = false;

    public string $icon;

    public string $key;

    public string $route;

    public ?string $permission = null;

    public ?string $parent = null;

    public Collection $children;

    public int $order = 0;

    public function __construct()
    {
        $this->children = collect();
    }

    public function setLabel(string $label): self
    {
        $this->label = $label;
        $this->translateLabel = str_starts_with($label, 'daylight::');

        return $this;
    }

    public function getLabel(): string
    {
        if ($this->translateLabel && function_exists('__')) {
            return __($this->label);
        }

        return $this->label;
    }

    public function setIcon(string $icon): self
    {
        $this->icon = $icon;

        return $this;
    }

    public function setKey(string $key): self
    {
        $this->key = $key;

        return $this;
    }

    public function setRoute(string $route): self
    {
        $this->route = $route;

        return $this;
    }

    public function setPermission(?string $permission): self
    {
        $this->permission = $permission;

        return $this;
    }

    public function setParent(?string $parent): self
    {
        $this->parent = $parent;

        return $this;
    }

    public function setOrder(int $order): self
    {
        $this->order = $order;

        return $this;
    }

    public function setChildren(Collection|array $children): self
    {
        if (is_array($children)) {
            $children = collect($children);
        }

        $this->children = $children->sortBy('order')->values();

        return $this;
    }

    public function getIcon(): string
    {
        if (! isset($this->icon)) {
            return 'o-home';
        }

        return $this->icon;
    }

    public function getUrl(): string
    {
        if (isset($this->route)) {
            return route($this->route);
        }

        return '#';
    }

    public function getChildren(): Collection
    {
        return $this->children;
    }

    public function isActive(): bool
    {
        if ($this->route === 'daylight.index') {
            return request()->routeIs($this->route);
        }

        return request()->routeIs($this->route) || request()->routeIs(Str::beforeLast($this->route, '.') . '.*') || $this->children->filter(fn ($c) => $c->getType() === 'item')->contains(fn (Page $child) => $child->isActive());
    }

    public function getType(): string
    {
        return 'item';
    }

    public function getOrder(): int
    {
        return $this->order;
    }

    public static function create(): self
    {
        return new self;
    }
}
