<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Auth;

final class DesignerAuthPageDefinition
{
    public function __construct(
        private readonly string $pageId,
        private readonly string $pageType,
        private readonly string $title,
        private readonly array $fields = [],
        private readonly array $actions = [],
        private readonly array $links = [],
        private readonly array $security = [],
        private readonly array $meta = []
    ) {}

    public static function create(string $pageType): self
    {
        $title = self::titleFor($pageType);
        return new self(
            $pageType,
            $pageType,
            $title,
            self::fieldsFor($pageType),
            self::actionsFor($pageType),
            self::linksFor($pageType),
            self::securityFor($pageType),
            ['version' => '1.0.0', 'createdAt' => date('c')]
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['pageId'] ?? $data['id'] ?? 'login'),
            (string) ($data['pageType'] ?? 'login'),
            (string) ($data['title'] ?? 'Login'),
            (array) ($data['fields'] ?? []),
            (array) ($data['actions'] ?? []),
            (array) ($data['links'] ?? []),
            (array) ($data['security'] ?? []),
            (array) ($data['meta'] ?? [])
        );
    }

    public function pageType(): string { return $this->pageType; }

    public function toComponent(): array
    {
        return [
            'id' => $this->pageId . '_auth_form',
            'name' => $this->pageId . '_auth_form',
            'type' => 'auth_form',
            'label' => $this->title,
            'props' => $this->toArray(),
            'children' => [],
            'events' => ['submit', 'validate', 'success', 'failure'],
            'meta' => ['designerRuntime' => 'auth', 'version' => '1.0.0'],
        ];
    }

    public function toPage(): array
    {
        return [
            'version' => '1.0',
            'pageId' => $this->pageId,
            'pageType' => $this->pageType,
            'title' => $this->title,
            'components' => [$this->toComponent()],
            'meta' => ['designerRuntime' => 'auth-page', 'generatedAt' => date('c')],
        ];
    }

    public function toArray(): array
    {
        return [
            'pageId' => $this->pageId,
            'id' => $this->pageId,
            'pageType' => $this->pageType,
            'title' => $this->title,
            'fields' => $this->fields,
            'actions' => $this->actions,
            'links' => $this->links,
            'security' => $this->security,
            'meta' => $this->meta,
            'fieldCount' => count($this->fields),
        ];
    }

    private static function titleFor(string $type): string
    {
        return match ($type) {
            'register' => 'Create Account',
            'forgot_password' => 'Forgot Password',
            'reset_password' => 'Reset Password',
            'change_password' => 'Change Password',
            'profile' => 'Profile',
            'user_info' => 'User Info',
            'access_denied' => 'Access Denied',
            default => 'Login',
        };
    }

    private static function fieldsFor(string $type): array
    {
        return match ($type) {
            'register' => [
                ['name' => 'name', 'type' => 'text', 'label' => 'Name', 'required' => true],
                ['name' => 'email', 'type' => 'email', 'label' => 'Email', 'required' => true],
                ['name' => 'password', 'type' => 'password', 'label' => 'Password', 'required' => true],
                ['name' => 'password_confirmation', 'type' => 'password', 'label' => 'Confirm Password', 'required' => true],
            ],
            'forgot_password' => [
                ['name' => 'email', 'type' => 'email', 'label' => 'Email', 'required' => true],
            ],
            'reset_password', 'change_password' => [
                ['name' => 'password', 'type' => 'password', 'label' => 'New Password', 'required' => true],
                ['name' => 'password_confirmation', 'type' => 'password', 'label' => 'Confirm Password', 'required' => true],
            ],
            'profile' => [
                ['name' => 'name', 'type' => 'text', 'label' => 'Name', 'required' => true],
                ['name' => 'email', 'type' => 'email', 'label' => 'Email', 'required' => true],
            ],
            'user_info' => [
                ['name' => 'name', 'type' => 'display', 'label' => 'Name'],
                ['name' => 'email', 'type' => 'display', 'label' => 'Email'],
                ['name' => 'role', 'type' => 'display', 'label' => 'Role'],
            ],
            'access_denied' => [],
            default => [
                ['name' => 'email', 'type' => 'email', 'label' => 'Email', 'required' => true],
                ['name' => 'password', 'type' => 'password', 'label' => 'Password', 'required' => true],
                ['name' => 'remember', 'type' => 'checkbox', 'label' => 'Remember me'],
            ],
        };
    }

    private static function actionsFor(string $type): array
    {
        return match ($type) {
            'register' => [['id' => 'register', 'label' => 'Register', 'variant' => 'primary']],
            'forgot_password' => [['id' => 'send_reset_link', 'label' => 'Send Reset Link', 'variant' => 'primary']],
            'reset_password' => [['id' => 'reset_password', 'label' => 'Reset Password', 'variant' => 'primary']],
            'change_password' => [['id' => 'change_password', 'label' => 'Change Password', 'variant' => 'primary']],
            'profile' => [['id' => 'save_profile', 'label' => 'Save Profile', 'variant' => 'primary']],
            'access_denied' => [['id' => 'go_back', 'label' => 'Go Back', 'variant' => 'secondary']],
            default => [['id' => 'login', 'label' => 'Login', 'variant' => 'primary']],
        };
    }

    private static function linksFor(string $type): array
    {
        return match ($type) {
            'login' => [
                ['label' => 'Create account', 'target' => 'register'],
                ['label' => 'Forgot password?', 'target' => 'forgot_password'],
            ],
            'register' => [['label' => 'Already have an account?', 'target' => 'login']],
            'forgot_password', 'reset_password' => [['label' => 'Back to login', 'target' => 'login']],
            default => [],
        };
    }

    private static function securityFor(string $type): array
    {
        return [
            'csrf' => true,
            'rateLimit' => in_array($type, ['login', 'forgot_password'], true),
            'guestOnly' => in_array($type, ['login', 'register', 'forgot_password', 'reset_password'], true),
            'authRequired' => in_array($type, ['profile', 'user_info', 'change_password'], true),
        ];
    }
}
