<?php

namespace App\Http\Resources;

use App\Traits\IconForType;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Http\Resources\MediaEntryResource;
use Mtc\ContentManager\Http\Resources\MenuView as BaseMenuView;
use Mtc\ContentManager\Traits\ContentMetaValues;
use Mtc\MercuryDataModels\MenuEntry;
use Mtc\MercuryDataModels\Page;
use Mtc\MercuryDataModels\VehicleMake;

class MenuView extends BaseMenuView
{
    use ContentMetaValues;
    use IconForType;

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $this->resource->load([
            'rootEntries.children.children.children',
            'rootEntries.mediaUses.media',
            'element.fields.childElement.fields',
        ]);
        $root_entries = $this->resource->rootEntries->map(fn ($entry) => $this->mapEntry($entry, true));
        $this->resource->entry_options = [
            'content' => [
                [
                    'icon' => 'input-pipe',
                    'name' => 'Custom URL',
                    'description' => 'Manually set URL',
                    'item_type' => 'custom',
                    'url' => '',
                    'custom_data' => [],
                ],
                [
                    'icon' => 'file-lines',
                    'name' => 'Content Page',
                    'item_type' => 'page',
                    'options' => 'pages',
                    'multiple_options' => false,
                    'description' => 'Select a content page',
                    'custom_data' => [],
                ],
                [
                    'icon' => 'cars',
                    'name' => 'Vehicle List Page',
                    'item_type' => 'filter',
                    'options' => 'makes',
                    'multiple_options' => true,
                    'description' => 'Link to a vehicle filter page',
                    'custom_data' => [],
                ],
                [
                    'icon' => 'badge-dollar',
                    'name' => 'Offer List Page',
                    'item_type' => 'offers',
                    'options' => 'makes',
                    'multiple_options' => false,
                    'description' => 'Link to an offer list page',
                    'custom_data' => [],
                ],
                [
                    'icon' => 'layer-group',
                    'name' => 'Group',
                    'item_type' => 'group',
                    'description' => 'Group with no URL',
                    'custom_data' => [],
                ],
            ],
            'options' => [
                'makes' => VehicleMake::query()->select(['id', 'name'])->get(),
                'pages' => Page::query()->active()->select(['id', 'title as name'])->get(),
            ],
        ];
        $data = $this->resource->toArray();

        $data['element_name'] = $this->resource->element?->title;
        $data['meta'] = $this->getMetaValues();
        $data['root_entries'] = $root_entries;
        $data['fields'] = $this->getFields();
        unset($data['element']);
        return $data;
    }

    protected function mapEntry(MenuEntry $entry, bool $topLevel = false)
    {
        return [
            'id' => $entry->id,
            'name' => $entry->name,
            'icon' => $this->getIcon($entry->item_type ?? ''),
            'active' => false,
            'url' => $entry->url,
            'item_type' => $entry->item_type,
            'item_id' => $entry->item_id,
            'is_enabled' => $entry->is_enabled,
            'custom_data' => $entry->data,
            'css_class' => $entry->css_class,
            'external' => $entry->external,
            'optionsMenuVisible' => false,
            'options' => $this->entryOptionValue($entry),
            'multiple_options' => $this->entryMultipleOptions($entry),
            'content' => $this->getContent($entry),
            'media' => $topLevel ? $entry->mediaUses->pluck('media_id') : [],
            'media_uses' => $topLevel
                ? $entry->mediaUses->map(fn (MediaUse $mediaUse) => new MediaEntryResource($mediaUse))
                : [],
            'children' => $entry->children->isNotEmpty()
                ? $entry->children->map(fn ($child) => $this->mapEntry($child))
                : []
        ];
    }

    private function getFields()
    {
        if (empty($this->resource->element)) {
            return collect([]);
        }

        return $this->resource->element->fields;
    }

    private function getContent(MenuEntry $entry)
    {
        return $this->getFields()
            ->keyBy(fn ($field) => $field->slug)
            ->map(fn ($field) => $entry->content[$field->slug] ?? '');
    }

    private function entryOptionValue(MenuEntry $entry): ?string
    {
        return match ($entry->item_type) {
            'page' => 'pages',
            'offers', 'filter' => 'makes',
            default => null,
        };
    }

    private function entryMultipleOptions(MenuEntry $entry)
    {

        return match ($entry->item_type) {
            'offers', 'page' => false,
            'filter' => 'true',
            default => false,
        };
    }
}
