/*
 * https://github.com/morethanwords/tweb
 * Copyright (C) 2019-2021 Eduard Kuzmenko
 * https://github.com/morethanwords/tweb/blob/master/LICENSE
 */

import {sessionAutoLoginService} from '../lib/api/sessionAutoLoginService';
import {logger} from '../lib/logger';

const log = logger('[page-auto-login]');

export default class PageAutoLogin {
  private pageEl: HTMLElement;
  private scrollable: HTMLElement;
  private dataParam: string | null = null;
  private isProcessing = false;

  constructor() {
    this.pageEl = document.getElementById('auth-pages')!;
    this.scrollable = this.pageEl.querySelector('.scrollable')!;

    log('Page elements found:', {
      pageEl: !!this.pageEl,
      scrollable: !!this.scrollable
    });
  }

  public async mount(): Promise<void> {
    log('Mounting auto login page');

    // 检查URL中是否有data参数
    this.dataParam = sessionAutoLoginService.parseUrlParams();
    if(!this.dataParam) {
      log('No data parameter found, redirecting to sign in');
      // 如果没有data参数，跳转到登录页面
      window.location.href = '/';
      return;
    }

    // 创建页面内容
    this.createPageContent();
  }

  private createPageContent(): void {
    log('Creating page content...');

    // 显示auth-pages元素
    this.pageEl.style.display = 'block';
    log('Made auth-pages visible');

    // 清空现有内容
    this.scrollable.innerHTML = '';
    log('Cleared scrollable content');

    // 创建容器
    const container = document.createElement('div');
    container.classList.add('auto-login-container');
    log('Created container element');

    // 创建登录按钮
    const loginButton = document.createElement('button');
    loginButton.classList.add('auto-login-button');
    loginButton.textContent = '登录';
    loginButton.addEventListener('click', () => this.handleAutoLogin());

    // 组装页面
    container.appendChild(loginButton);

    this.scrollable.appendChild(container);
    log('Appended container to scrollable');

    // 添加样式
    this.addStyles();
    log('Added styles to page');

    // 验证页面内容
    const createdElements = this.scrollable.querySelectorAll('.auto-login-container');
    log('Page content verification:', {
      containerExists: createdElements.length > 0,
      containerChildren: createdElements[0]?.children.length || 0
    });
  }

  private async handleAutoLogin(): Promise<void> {
    if(this.isProcessing) return;

    this.isProcessing = true;
    const loginButton = this.scrollable.querySelector('.auto-login-button') as HTMLButtonElement;

    // 禁用按钮
    loginButton.disabled = true;

    try {
      // 检查是否存在旧的会话数据，如果存在则清理
      const hasExistingData = await sessionAutoLoginService.hasExistingSessionData();
      if(hasExistingData) {
        log('Found existing session data, clearing before login...');
        await sessionAutoLoginService.clearAllSessionData();
        log('Old session data cleared successfully');
      } else {
        log('No existing session data found, proceeding with login');
      }

      // Session数据注入按钮点击事件
      const sessionData = this.dataParam;
      if(!sessionData) {
        loginButton.disabled = false;
        this.isProcessing = false;
        return;
      }

      // 尝试解析Base64数据
      let parsedData;
      try {
        const decodedString = atob(sessionData);
        parsedData = JSON.parse(decodedString);
      } catch(e) {
        // 如果不是Base64，尝试直接解析JSON
        try {
          parsedData = JSON.parse(sessionData);
        } catch(e2) {
          throw new Error('数据格式无效，请确保输入正确的Base64编码或JSON数据');
        }
      }

      // 验证数据格式
      if(!parsedData || typeof parsedData !== 'object') {
        throw new Error('数据格式无效');
      }

      // 查找登录相关的数据
      const loginKeys = ['dc', 'dcId', 'serverTimeOffset', 'auth_key', 'user_id', 'userId', 'session'];
      const foundLoginData: any = {};
      for(const key of loginKeys) {
        if(parsedData[key] !== undefined) {
          foundLoginData[key] = parsedData[key];
        }
      }

      // 检查是否有足够的登录数据
      if(Object.keys(foundLoginData).length === 0) {
        throw new Error('未找到有效的登录数据，请确保数据包含dc、auth_key等信息');
      }

      // 显示找到的登录数据
      console.log('找到的登录数据:', foundLoginData);

      // 将解析后的数据重新注入到localStorage中
      let injectedCount = 0;
      for(const [key, value] of Object.entries(parsedData)) {
        try {
          localStorage.setItem(key, JSON.stringify(value));
          injectedCount++;
        } catch(e) {
          console.warn(`无法注入键 ${key}:`, e);
        }
      }

      // 清除URL参数
      sessionAutoLoginService.clearUrlParams();

      // 标记这是通过URL参数自动登录的，跳过转圈圈页面
      localStorage.setItem('autoLoginFromUrl', 'true');

      // 自动刷新页面以应用新的localStorage数据
      setTimeout(() => {
        window.location.reload();
      }, 1500);
    } catch(error) {
      log('Error during auto login:', error);

      // 重新启用按钮
      loginButton.disabled = false;
    }

    this.isProcessing = false;
  }

  private addStyles(): void {
    const style = document.createElement('style');
    style.textContent = `
      .auto-login-container {
        max-width: 500px;
        margin: 0 auto;
        padding: 40px 20px;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
      }

      .auto-login-button {
        background: var(--primary-color);
        color: white;
        border: none;
        border-radius: 8px;
        padding: 15px 30px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        margin-right: 15px;
        transition: background-color 0.2s;
      }

      .auto-login-button:hover:not(:disabled) {
        background: #4CAF50;
      }

      .auto-login-button:disabled {
        background: var(--disabled-color);
        cursor: not-allowed;
      }

      @media (max-width: 768px) {
        .auto-login-container {
          padding: 20px 15px;
        }

        .auto-login-button {
          width: 100%;
          margin: 5px 0;
        }
      }
    `;

    document.head.appendChild(style);
  }
}
