<?php

namespace Daylight\Core\Http\Requests\Store\Categories;

use Daylight\Core\Http\Requests\Concerns\HandlesSeoRequest;
use Daylight\Core\Models\Enums\DisplayType;
use Daylight\Core\Modules\PageBuilder\Concerns\InteractsWithPageBuilder;
use Daylight\Core\Modules\PageBuilder\Contracts\HasPageBuilder;
use Daylight\Core\Modules\PageBuilder\Registries\ComponentRegistry;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreCategoryRequest extends FormRequest implements HasPageBuilder
{
    use HandlesSeoRequest;
    use InteractsWithPageBuilder;

    public function authorize(): bool
    {
        return auth()->check() && auth()->user()->can('create:categories');
    }

    public function rules(): array
    {
        return [
            'parent_id' => ['nullable', 'exists:categories,id'],
            'order' => ['required', 'integer'],
            'display' => ['required', Rule::in(DisplayType::cases())],
            'manual_sorting' => ['required', 'boolean'],
            'name' => ['required', 'string', 'max:255'],
            'content' => ['nullable', 'string'],
            'locale' => ['required', 'string', 'max:255'],
            ...$this->getSeoRules(),
            ...$this->getPageBuilderRules(
                required: false
            ),
        ];
    }

    public function messages(): array
    {
        $messages = [
            'components.required' => __('daylight::general.page_builder.components_required'),
            'components.*.type.required' => __('daylight::general.page_builder.component_type_required'),
            'components.*.data.required' => __('daylight::general.page_builder.component_data_required'),
        ];

        // Generate messages for component fields dynamically
        $registry = app(ComponentRegistry::class);
        $components = $this->input('components', []);

        if (is_string($components)) {
            $components = json_decode($components, true) ?: [];
        }

        if (! is_array($components)) {
            return $messages;
        }

        foreach ($components as $index => $component) {
            if (! isset($component['type']) || ! is_array($component)) {
                continue;
            }

            $definition = $registry->getDefinition($component['type']);
            if (! $definition) {
                continue;
            }

            $componentName = $definition->name();

            foreach ($definition->fields() as $field) {
                $fieldPath = "components.{$index}.data.{$field->name}";
                $fieldLabel = $field->label;

                // Required messages
                $messages["{$fieldPath}.required"] = __('daylight::general.page_builder.field_required', [
                    'field' => strtolower($fieldLabel),
                    'component' => $componentName,
                    'index' => $index + 1,
                ]);

                // Type-specific messages
                switch ($field->type) {
                    case 'media':
                        $messages["{$fieldPath}.min"] = __('daylight::general.page_builder.field_min_items', [
                            'field' => strtolower($fieldLabel),
                            'component' => $componentName,
                            'min' => 1,
                            'index' => $index + 1,
                        ]);
                        $messages["{$fieldPath}.*.id.required"] = __('daylight::general.page_builder.field_invalid_media', [
                            'field' => strtolower($fieldLabel),
                            'component' => $componentName,
                            'index' => $index + 1,
                        ]);
                        $messages["{$fieldPath}.*.id.exists"] = __('daylight::general.page_builder.field_invalid_media', [
                            'field' => strtolower($fieldLabel),
                            'component' => $componentName,
                            'index' => $index + 1,
                        ]);
                        break;

                    case 'related':
                        $messages["{$fieldPath}.*.id.required"] = __('daylight::general.page_builder.field_invalid', [
                            'field' => strtolower($fieldLabel),
                            'component' => $componentName,
                            'index' => $index + 1,
                        ]);
                        $messages["{$fieldPath}.*.id.integer"] = __('daylight::general.page_builder.field_must_be_valid', [
                            'field' => strtolower($fieldLabel),
                            'component' => $componentName,
                            'index' => $index + 1,
                        ]);
                        break;

                    case 'repeater':
                        foreach ($field->items as $subField) {
                            $subFieldPath = "{$fieldPath}.*.{$subField->name}";
                            $subFieldLabel = $subField->label;

                            $messages["{$subFieldPath}.required"] = __('daylight::general.page_builder.row_required', [
                                'field' => strtolower($subFieldLabel),
                                'component' => $componentName,
                                'index' => $index + 1,
                            ]);

                            if ($subField->type === 'media') {
                                $messages["{$subFieldPath}.*.id.required"] = __('daylight::general.page_builder.row_invalid_media', [
                                    'field' => strtolower($subFieldLabel),
                                    'component' => $componentName,
                                    'index' => $index + 1,
                                ]);
                                $messages["{$subFieldPath}.*.id.exists"] = __('daylight::general.page_builder.row_invalid_media', [
                                    'field' => strtolower($subFieldLabel),
                                    'component' => $componentName,
                                    'index' => $index + 1,
                                ]);
                            }
                        }
                        break;
                }
            }
        }

        return $messages;
    }

    public function attributes(): array
    {
        $attributes = [
            'locale' => __('daylight::general.locale'),
            'name' => __('daylight::general.name'),
            'slug' => __('daylight::general.slug'),
            'template' => __('daylight::general.template'),
            'components' => __('daylight::general.components'),
        ];

        // Generate friendly attribute names for component fields
        $registry = app(ComponentRegistry::class);
        $components = $this->input('components', []);

        if (is_string($components)) {
            $components = json_decode($components, true) ?: [];
        }

        if (! is_array($components)) {
            return $attributes;
        }

        foreach ($components as $index => $component) {
            if (! isset($component['type']) || ! is_array($component)) {
                continue;
            }

            $definition = $registry->getDefinition($component['type']);
            if (! $definition) {
                continue;
            }

            $componentName = $definition->name();

            foreach ($definition->fields() as $field) {
                $fieldPath = "components.{$index}.data.{$field->name}";
                $attributes[$fieldPath] = "{$field->label} ({$componentName})";

                // Handle nested fields (buttons, repeaters, etc.)
                if ($field->type === 'button') {
                    $attributes["{$fieldPath}.url"] = "{$field->label} - " . __('daylight::general.url');
                    $attributes["{$fieldPath}.label"] = "{$field->label} - " . __('daylight::general.label');
                }

                if ($field->type === 'repeater') {
                    foreach ($field->items as $subField) {
                        $subFieldPath = "{$fieldPath}.*.{$subField->name}";
                        $attributes[$subFieldPath] = "{$field->label} - {$subField->label} ({$componentName})";
                    }
                }
            }
        }

        return $attributes;
    }
}
