import type { AuthorizationRequest } from '../../types';

/**
 * 页面配置接口
 */
export interface PageConfig {
    /** 页面标题 */
    title?: string;
    /** 品牌名称 */
    brandName?: string;
    /** 自定义CSS */
    customCSS?: string;
    /** 自定义Logo URL */
    logoUrl?: string;
}

/**
 * HTML模板工具类
 */
export class HtmlTemplates {
    private static readonly DEFAULT_TITLE = '用户登录';
    private static readonly DEFAULT_BRAND_NAME = 'OIDC Provider';

    /**
     * 生成登录页面HTML
     */
    static generateLoginPage(
        authRequest: AuthorizationRequest,
        config: PageConfig = {},
        error?: string
    ): string {
        const {
            title = this.DEFAULT_TITLE,
            brandName = this.DEFAULT_BRAND_NAME,
            customCSS = '',
            logoUrl
        } = config;

        return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${this.escapeHtml(title)}</title>
    <style>
        ${this.getDefaultStyles()}
        ${customCSS}
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            ${logoUrl ? `<img src="${this.escapeHtml(logoUrl)}" alt="Logo" class="logo" />` : ''}
            <h1>${this.escapeHtml(brandName)}</h1>
            <p>请登录以继续访问应用</p>
        </div>
        
        <form class="login-form" method="POST" action="/oidc/login">
            ${error ? `<div class="error-message">${this.escapeHtml(error)}</div>` : ''}
            
            <div class="client-info">
                <h3>应用授权</h3>
                <p>应用 <strong>${this.escapeHtml(authRequest.client_id)}</strong> 请求访问您的账户信息</p>
                <p class="scope-info">权限范围: <code>${this.escapeHtml(authRequest.scope)}</code></p>
            </div>
            
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" required autocomplete="username" />
            </div>
            
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required autocomplete="current-password" />
            </div>
            
            <div class="checkbox-group">
                <input type="checkbox" id="remember_me" name="remember_me" />
                <label for="remember_me">记住我</label>
            </div>
            
            ${this.generateHiddenFields(authRequest)}
            
            <button type="submit" class="login-button">登录</button>
        </form>
    </div>
</body>
</html>`;
    }

    /**
     * 生成错误页面HTML
     */
    static generateErrorPage(
        error: string,
        description?: string,
        config: PageConfig = {}
    ): string {
        const {
            title = '认证错误',
            brandName = this.DEFAULT_BRAND_NAME
        } = config;

        return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${this.escapeHtml(title)}</title>
    <style>
        ${this.getDefaultStyles()}
        .error-container {
            max-width: 500px;
            margin: 2rem auto;
            padding: 2rem;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        .error-icon {
            font-size: 3rem;
            color: #dc2626;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <div class="error-container">
        <div class="error-icon">⚠️</div>
        <h1>${this.escapeHtml(brandName)}</h1>
        <h2>认证失败</h2>
        <div class="error-message">
            <strong>${this.escapeHtml(error)}</strong>
            ${description ? `<p>${this.escapeHtml(description)}</p>` : ''}
        </div>
        <button onclick="history.back()" class="login-button" style="margin-top: 1rem;">返回</button>
    </div>
</body>
</html>`;
    }

    /**
     * 获取默认样式
     */
    private static getDefaultStyles(): string {
        return `
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .login-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            max-width: 400px;
            width: 100%;
        }
        
        .login-header {
            background: #4f46e5;
            color: white;
            padding: 2rem;
            text-align: center;
        }
        
        .logo {
            max-width: 60px;
            height: auto;
            margin-bottom: 1rem;
            border-radius: 8px;
        }
        
        .login-header h1 {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
        }
        
        .login-header p {
            opacity: 0.9;
            font-size: 0.875rem;
        }
        
        .login-form {
            padding: 2rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #374151;
        }
        
        .form-group input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 1rem;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        
        .checkbox-group input {
            margin-right: 0.5rem;
        }
        
        .checkbox-group label {
            margin: 0;
            font-weight: normal;
            font-size: 0.875rem;
            color: #6b7280;
            cursor: pointer;
        }
        
        .login-button {
            width: 100%;
            background: #4f46e5;
            color: white;
            border: none;
            border-radius: 6px;
            padding: 0.75rem;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .login-button:hover {
            background: #4338ca;
        }
        
        .login-button:active {
            background: #3730a3;
        }
        
        .error-message {
            background: #fee2e2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 0.75rem;
            border-radius: 6px;
            margin-bottom: 1.5rem;
            font-size: 0.875rem;
        }
        
        .client-info {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .client-info h3 {
            font-size: 0.875rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .client-info p {
            font-size: 0.75rem;
            color: #6b7280;
            margin-bottom: 0.25rem;
        }
        
        .scope-info code {
            background: #e5e7eb;
            padding: 0.125rem 0.25rem;
            border-radius: 3px;
            font-size: 0.7rem;
        }
    `;
    }

    /**
     * 生成隐藏字段
     */
    private static generateHiddenFields(authRequest: AuthorizationRequest): string {
        const fields = [
            { name: 'response_type', value: authRequest.response_type },
            { name: 'client_id', value: authRequest.client_id },
            { name: 'redirect_uri', value: authRequest.redirect_uri },
            { name: 'scope', value: authRequest.scope },
        ];

        // 可选字段
        if (authRequest.state) fields.push({ name: 'state', value: authRequest.state });
        if (authRequest.nonce) fields.push({ name: 'nonce', value: authRequest.nonce });
        if (authRequest.code_challenge) fields.push({ name: 'code_challenge', value: authRequest.code_challenge });
        if (authRequest.code_challenge_method) fields.push({ name: 'code_challenge_method', value: authRequest.code_challenge_method });

        return fields
            .map(field => `<input type="hidden" name="${this.escapeHtml(field.name)}" value="${this.escapeHtml(field.value)}" />`)
            .join('\n            ');
    }

    /**
     * 转义HTML字符
     */
    private static escapeHtml(unsafe: string): string {
        return unsafe
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }
} 