<?php

namespace apexl\Io\modules\userDisplay\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\HookManager;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\component\Factories\GenericComponentFactory;
use apexl\Io\modules\display\ComponentFactory\FormComponentFactory;
use apexl\Io\modules\display\ComponentFactory\FormFieldComponentFactory;
use apexl\Io\modules\display\ComponentFactory\InputFieldComponentFactory;
use apexl\Io\modules\display\components\BasicLink;
use apexl\Io\modules\display\components\ContentTitle;
use apexl\Io\modules\display\components\form\EmailField;
use apexl\Io\modules\display\components\form\HiddenField;
use apexl\Io\modules\display\components\form\PasswordField;
use apexl\Io\modules\display\services\Render;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\CurrentUserFactory;
use apexl\Io\services\VariableManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

;

final readonly class LoginDisplayController extends Controller
{
    public function __invoke(
        Render $render,
        RouteManager $routeManager,
        CurrentUserFactory $currentUserFactory,
        GenericComponentFactory $componentFactory,
        FormComponentFactory $formComponentFactory,
        FormFieldComponentFactory $formFieldComponentFactory,
        VariableManager $variableManager,
        HookManager $hookManager,
        ServerRequestInterface $request,
        ResponseInterface $response,
        ?string $loginMessageType = null
    ): ResponseInterface {
        if ($this->redirectIfLoggedIn($currentUserFactory->get())) {
            return $this->json($response);
        }

        $render->setActive('noUI');
        $render->setPageTitle('Login');
        $components = $hookManager->processHook('login_page_components_before_form', []);

        if ($loginMessageType && $message = config(sprintf('auth.login_messages.%s', $loginMessageType))) {
            $components[] = $componentFactory->make(ContentTitle::class)
                ->addContent($message)
                ->addClass('text-light');
        }

        $form = $formComponentFactory->make()
            ->title($variableManager->get('user_login_description_text') ?? "Sign in with your email address.")
            ->setMethod('post')
            ->setActionUrl($routeManager->getRoutePattern('user.login'))
            ->setSubmitText($variableManager->get('user_login_submit_text') ?? 'Sign in')
            ->addClass('login-form');
        if ($variableManager->get('user_login_include_clear_button') ?? true) {
            $form->includeClearButton()->setClearButtonText(
                $variableManager->get('user_login_include_clear_button_text') ?? 'Cancel'
            );
        }

        $redirect = ($request->getQueryParams()['redirect'] ?? null);
        if ($redirect) {
            $form->addField(
                $formFieldComponentFactory
                    ->make(HiddenField::class, 'redirect')
                    ->setValue($redirect)
            );
        }

        $form->addField(
            $formFieldComponentFactory->make(EmailField::class, 'username')
                ->setPlaceholder($variableManager->get('user_login_email_placeholder') ?? 'Enter your email address')
                ->setLabel('Email')
                ->hideLabel()
                ->isRequired()
        );
        $form->addField(
            $formFieldComponentFactory->make(PasswordField::class, 'password')
                ->setPlaceholder($variableManager->get('user_login_password_placeholder') ?? 'Enter your password')
                ->setLabel('Password')
                ->hideLabel()
                ->isRequired()
        );

        $components = [
            ...$components,
            $form,
            $componentFactory->make(BasicLink::class)
                ->addClass('forgottenPasswordLink')
                ->addRoute($routeManager->getRoutePattern('user.display.forgot-password'))
                ->addText($variableManager->get('user_login_forgot_password_text') ?? 'Forgot password?'),

        ];
        if (config('auth.users_can_register')) {
            $components[] = $componentFactory->make(BasicLink::class)
                ->addClass('registerLink')
                ->addRoute($routeManager->getRoutePattern('user.display.register'))
                ->addText($variableManager->get('user_login_register_text') ?? 'No account? Register.');
        }


        $components = $hookManager->processHook('login_page_components_after_form', $components);

        return $this->json($response, $render->build($components));
    }

    protected function redirectIfLoggedIn(userEntity $user): bool
    {
        if ($user->isLoggedIn()) {
            $this->output->addMetadata('user.login.redirect', 'redirect', '/');

            return true;
        }

        return false;
    }

}
