<?php

namespace App\Livewire\Admin;

use App\Models\Page;
use Livewire\Component;
use App\Models\PageItem;
use App\Services\Models\FileService;

class PageItemEdit extends Component
{
    public Page $page;
    public array $items = [];
    public array $components = [];

    protected $listeners = ['file-uploaded' => 'handleFileUploaded'];

    public function mount(Page $page)
    {
        $this->page = $page;

        $this->components = app('page-builder.components')
            ->mapWithKeys(fn($c) => [$c::name() => $c])
            ->toArray();

        $this->items = $page->items()->orderBy('order')->get()->map(function ($item) {
            return [
                'id' => $item->id,
                'component' => $item->component,
                'settings' => $item->settings ?? [],
            ];
        })->toArray();
    }

    public function addComponent($componentName)
    {
        if (!isset($this->components[$componentName])) return;

        $componentClass = $this->components[$componentName];

        $defaultSettings = [];
        foreach ($componentClass::fields() as $field) {
            $defaultSettings[$field['name']] = $field['type'] === 'repeater' ? [[]] : '';
        }

        $this->items[] = [
            'id' => null,
            'component' => $componentClass::name(),
            'settings' => $defaultSettings,
        ];
    }

    public function removeItem($index)
    {
        if (isset($this->items[$index]['id'])) {
            PageItem::where('id', $this->items[$index]['id'])->delete();
        }
        unset($this->items[$index]);
        $this->items = array_values($this->items);
    }

    public function addRepeater($itemIndex, $field)
    {
        $this->items[$itemIndex]['settings'][$field][] = [];
    }

    public function removeRepeater($itemIndex, $field, $subIndex)
    {
        unset($this->items[$itemIndex]['settings'][$field][$subIndex]);
        $this->items[$itemIndex]['settings'][$field] = array_values($this->items[$itemIndex]['settings'][$field]);
    }

    public function handleFileUploaded(string $url, string $model)
    {
        data_set($this, $model, $url);
    }

    public function save()
    {
        foreach ($this->items as $i => &$item) {
            $componentClass = $this->components[$item['component']] ?? null;
            if (!$componentClass) continue;

            foreach ($componentClass::fields() as $field) {
                $name = $field['name'];
                $type = $field['type'] ?? 'text';

                if ($type === 'repeater') {
                    foreach ($item['settings'][$name] ?? [] as $subIndex => &$subItem) {
                        foreach ($field['fields'] as $subField) {
                            $subName = $subField['name'];
                            $subType = $subField['type'] ?? 'text';
                            if ($subType === 'image') {
                                $fileData = data_get($this->items, "$i.settings.$name.$subIndex.{$subName}_upload");
                                if ($fileData instanceof \Illuminate\Http\UploadedFile) {
                                    $upload = (new FileService)->upload($fileData);
                                    $subItem[$subName] = asset('storage/' . $upload['path']);
                                }
                            }
                        }
                    }
                } elseif ($type === 'image') {
                    $fileData = data_get($this->items, "$i.settings.{$name}_upload");
                    if ($fileData instanceof \Illuminate\Http\UploadedFile) {
                        $upload = (new FileService)->upload($fileData);
                        $item['settings'][$name] = asset('storage/' . $upload['path']);
                    }
                }
            }

            PageItem::updateOrCreate(
                ['id' => $item['id']],
                [
                    'page_id' => $this->page->id,
                    'component' => $item['component'],
                    'order' => $i,
                    'settings' => $item['settings'],
                ]
            );
        }

        session()->flash('message', 'Page items saved successfully!');
    }

    public function render()
    {
        return view('livewire.admin.page-item-edit')->extends('layouts.syndron.app')->section('content');
    }
}
