<?php

declare(strict_types=1);

namespace UFPE\GoogleOIDC;

final class LoginUI
{
    private Config $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function register(): void
    {
        add_filter('login_message', [$this, 'message']);
        add_action('login_form', [$this, 'nativeLoginFormHook']);
        add_filter('login_form_middle', [$this, 'embeddedLoginFormHook'], 10, 2);
        add_filter('login_body_class', [$this, 'bodyClass']);
        add_action('login_enqueue_scripts', [$this, 'styles']);
    }

    public function message(string $message): string
    {
        if ($this->isLocalLogin()) {
            return $message . '<p class="message">Acesso administrativo local de contingencia.</p>';
        }

        $error = $this->errorMessage();
        $html = $message;

        if ($error !== '') {
            $html .= '<div id="login_error">' . esc_html($error) . '</div>';
        }

        $html .= '<div class="message ufpe-google-login-message">';
        $html .= '<p><strong>Acesso restrito UFPE.</strong> Use sua conta Google institucional.</p>';
        $html .= '<p><a class="button button-primary button-large ufpe-google-button" href="' . esc_url($this->config->startUri($this->redirectTo())) . '">Entrar com Google UFPE</a></p>';
        $html .= '<p class="ufpe-local-login-link"><a href="' . esc_url(add_query_arg('local', '1', network_site_url('wp-login.php', 'login'))) . '">Acesso administrativo local</a></p>';
        $html .= '</div>';

        return $html;
    }

    public function nativeLoginFormHook(): void
    {
        do_action('ufpe_google_oidc_login_form_rendered');
    }

    public function embeddedLoginFormHook(string $content, array $args): string
    {
        if ($this->isLocalLogin()) {
            return $content;
        }

        return $content . '<p><a class="button button-primary ufpe-google-button" href="' . esc_url($this->config->startUri($this->redirectTo())) . '">Entrar com Google UFPE</a></p>';
    }

    public function bodyClass(array $classes): array
    {
        $classes[] = $this->isLocalLogin() ? 'ufpe-local-login' : 'ufpe-google-login';
        return $classes;
    }

    public function styles(): void
    {
        ?>
        <style>
            body.ufpe-google-login #loginform { display: none; }
            .ufpe-google-button { width: 100%; text-align: center; }
            .ufpe-local-login-link { font-size: 12px; text-align: center; }
        </style>
        <?php
    }

    private function isLocalLogin(): bool
    {
        return isset($_GET['local']) && $_GET['local'] === '1';
    }

    private function redirectTo(): string
    {
        return isset($_REQUEST['redirect_to'])
            ? wp_validate_redirect(esc_url_raw(wp_unslash((string) $_REQUEST['redirect_to'])), admin_url())
            : admin_url();
    }

    private function errorMessage(): string
    {
        $code = isset($_GET['ufpe_google_error'])
            ? sanitize_key(wp_unslash((string) $_GET['ufpe_google_error']))
            : '';

        $messages = [
            'config' => 'Login Google ainda nao configurado.',
            'state' => 'Sessao de login invalida. Tente novamente.',
            'state_expired' => 'Sessao de login expirada. Tente novamente.',
            'ufpe_google_invalid_domain' => 'Conta Google fora do dominio institucional UFPE.',
            'ufpe_google_unverified_email' => 'A conta Google nao possui e-mail verificado.',
            'ufpe_google_user_blocked' => 'Usuario bloqueado localmente.',
            'ufpe_google_provisioning_disabled' => 'Conta institucional sem provisionamento local autorizado.',
        ];

        return $messages[$code] ?? ($code ? 'Nao foi possivel concluir o login institucional.' : '');
    }
}
