/**
 * @name 登录页
 * 
 * 参考资料：
 * - /rules/development-standards.md
 * - /rules/axure-api-guide.md
 * - /src/themes/antd-new/designToken.json
 * - /assets/libraries/antd.md
 */

import './style.css';
import React, { useState, useCallback, useImperativeHandle, forwardRef, useEffect } from 'react';
import { 
  Layout, 
  Tabs, 
  Form, 
  Input, 
  Button, 
  Checkbox, 
  message, 
  Modal, 
  Card, 
  List, 
  Avatar, 
  Typography, 
  QRCode, 
  Space,
  Divider,
  Alert
} from 'antd';
import { 
  UserOutlined, 
  LockOutlined, 
  SafetyCertificateOutlined, 
  ScanOutlined, 
  MobileOutlined,
  GlobalOutlined,
  RightOutlined
} from '@ant-design/icons';

import type {
  KeyDesc,
  DataDesc,
  ConfigItem,
  Action,
  EventItem,
  AxureProps,
  AxureHandle
} from '../../common/axure-types';

const { Title, Text, Paragraph } = Typography;

// --- Axure API Definitions ---

const EVENT_LIST: EventItem[] = [
  { name: 'onLoginSuccess', desc: '登录成功并选择租户后触发', payload: 'JSON string' },
  { name: 'onLoginFail', desc: '登录失败时触发', payload: 'string' }
];

const ACTION_LIST: Action[] = [
  { name: 'resetForm', desc: '重置登录表单' }
];

const VAR_LIST: KeyDesc[] = [
  { name: 'current_user', desc: '当前登录用户信息' },
  { name: 'current_tenant', desc: '当前选中的企业租户' }
];

const CONFIG_LIST: ConfigItem[] = [
  { type: 'input', attributeId: 'systemName', displayName: '系统名称', info: '登录页显示的系统名称', initialValue: '企业微信私域运营系统' },
  { type: 'input', attributeId: 'backgroundUrl', displayName: '背景图URL', info: '左侧背景图片地址', initialValue: '' }
];

const DATA_LIST: DataDesc[] = [
  {
    name: 'tenants',
    desc: '可供选择的企业租户列表',
    keys: [
      { name: 'id', desc: '企业ID' },
      { name: 'name', desc: '企业名称' },
      { name: 'logo', desc: '企业Logo URL' }
    ]
  }
];

// --- Mock Data ---

const MOCK_TENANTS = [
  { id: 'T001', name: '未来科技集团', logo: 'https://api.dicebear.com/7.x/initials/svg?seed=FT' },
  { id: 'T002', name: '创新动力实验室', logo: 'https://api.dicebear.com/7.x/initials/svg?seed=CL' },
  { id: 'T003', name: '云端智能解决方案', logo: 'https://api.dicebear.com/7.x/initials/svg?seed=CS' }
];

// --- Component ---

const Component = forwardRef<AxureHandle, AxureProps>(function LoginPage(innerProps, ref) {
  const dataSource = innerProps && innerProps.data ? innerProps.data : {};
  const configSource = innerProps && innerProps.config ? innerProps.config : {};
  const onEventHandler = typeof innerProps.onEvent === 'function' ? innerProps.onEvent : () => undefined;

  // Config
  const systemName = configSource.systemName || '企业微信私域运营系统';
  
  // State
  const [activeTab, setActiveTab] = useState<string>('account');
  const [loginLoading, setLoginLoading] = useState(false);
  const [tenantModalOpen, setTenantModalOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [currentTenant, setCurrentTenant] = useState<any>(null);
  const [errorCount, setErrorCount] = useState(0);
  const [showError, setShowError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  
  const [form] = Form.useForm();
  const [scanForm] = Form.useForm();

  // Data
  const tenants = Array.isArray(dataSource.tenants) && dataSource.tenants.length > 0 
    ? dataSource.tenants 
    : MOCK_TENANTS;

  // Axure API Handler
  const emitEvent = useCallback((eventName: string, payload?: any) => {
    try {
      const payloadStr = typeof payload === 'object' ? JSON.stringify(payload) : String(payload || '');
      onEventHandler(eventName, payloadStr);
    } catch (error) {
      console.warn('onEvent trigger failed:', error);
    }
  }, [onEventHandler]);

  useImperativeHandle(ref, () => ({
    getVar: (name: string) => {
      const vars: Record<string, any> = { 
        current_user: currentUser,
        current_tenant: currentTenant 
      };
      return vars[name];
    },
    fireAction: (name: string) => {
      if (name === 'resetForm') {
        form.resetFields();
        scanForm.resetFields();
        setErrorCount(0);
        setShowError(false);
      }
    },
    eventList: EVENT_LIST,
    actionList: ACTION_LIST,
    varList: VAR_LIST,
    configList: CONFIG_LIST,
    dataList: DATA_LIST
  }));

  // Logic
  const handleAccountLogin = async (values: any) => {
    setLoginLoading(true);
    setShowError(false);

    // Simulation: artificial delay
    await new Promise(resolve => setTimeout(resolve, 1000));

    // Mock Validation
    // In real scenario, this would call backend API
    if (values.password === 'error' || errorCount > 5) {
      // Simulate brute force protection or error
      setErrorCount(prev => prev + 1);
      setShowError(true);
      setErrorMessage(errorCount > 3 ? '尝试次数过多，请稍后再试' : '账号或密码错误，请重试');
      emitEvent('onLoginFail', 'Account or password error');
      setLoginLoading(false);
      return;
    }

    // Success
    const user = { id: 'U1001', name: values.username || 'Admin' };
    setCurrentUser(user);
    setLoginLoading(false);
    
    // Open Tenant Selection
    setTenantModalOpen(true);
  };

  const handleScanLogin = async (values: any) => {
    setLoginLoading(true);
    // Simulate verification
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    if (values.dynamicCode !== '123456') { // Mock correct code
      message.error('动态验证码错误');
      setLoginLoading(false);
      return;
    }

    const user = { id: 'U1002', name: 'ScanUser' };
    setCurrentUser(user);
    setLoginLoading(false);
    setTenantModalOpen(true);
  };

  const handleTenantSelect = (tenant: any) => {
    setCurrentTenant(tenant);
    setTenantModalOpen(false);
    message.success(`欢迎进入 ${tenant.name}`);
    
    // Trigger success event
    emitEvent('onLoginSuccess', { 
      user: currentUser, 
      tenant: tenant 
    });

    // Navigate to dashboard
    setTimeout(() => {
      window.location.href = `/prototypes/ai-complete-3?tenantId=${tenant.id}&tenantName=${encodeURIComponent(tenant.name)}`;
    }, 1000);
  };

  return (
    <div className="login-page-container">
      {/* Left Panel */}
      <div className="login-left-panel">
        <div className="login-branding">
          <h1 className="brand-title">{systemName}</h1>
          <p className="brand-subtitle">
            连接企业未来，驱动创新增长<br/>
            Secure • Efficient • Intelligent
          </p>
        </div>
      </div>

      {/* Right Panel */}
      <div className="login-right-panel">
        <div className="login-form-container">
          <div className="login-header">
            <Title level={2}>欢迎登录</Title>
            <Text type="secondary">请选择登录方式进入系统</Text>
          </div>

          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            className="login-tabs"
            items={[
              {
                key: 'account',
                label: <span><UserOutlined /> 账号密码登录</span>,
                children: (
                  <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleAccountLogin}
                    size="large"
                  >
                    {showError && (
                      <Alert 
                        message={errorMessage} 
                        type="error" 
                        showIcon 
                        style={{ marginBottom: 24 }} 
                      />
                    )}

                    <Form.Item
                      name="username"
                      rules={[{ required: true, message: '请输入账号' }]}
                    >
                      <Input prefix={<UserOutlined />} placeholder="请输入账号 / 手机号 / 邮箱" />
                    </Form.Item>

                    <Form.Item
                      name="password"
                      rules={[{ required: true, message: '请输入密码' }]}
                    >
                      <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
                    </Form.Item>

                    <Form.Item
                      name="captcha"
                      rules={[{ required: true, message: '请输入验证码' }]}
                    >
                      <div style={{ display: 'flex', gap: 8 }}>
                        <Input prefix={<SafetyCertificateOutlined />} placeholder="验证码" />
                        <img 
                          src="https://placehold.co/100x40/e6f7ff/1890ff?text=AB12" 
                          alt="captcha" 
                          style={{ cursor: 'pointer', height: 40, borderRadius: 6 }}
                          onClick={() => message.info('刷新验证码')}
                        />
                      </div>
                    </Form.Item>

                    <Form.Item>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Checkbox>记住我</Checkbox>
                        <a onClick={(e) => e.preventDefault()}>忘记密码？</a>
                      </div>
                    </Form.Item>

                    <Form.Item>
                      <Button type="primary" htmlType="submit" block loading={loginLoading}>
                        登 录
                      </Button>
                    </Form.Item>
                  </Form>
                )
              },
              {
                key: 'scan',
                label: <span><ScanOutlined /> 扫码登录</span>,
                children: (
                  <div className="scan-login-container">
                    <div className="qrcode-wrapper">
                      <QRCode 
                        value="https://example.com/login?token=xyz" 
                        size={180} 
                        icon="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
                      />
                    </div>
                    <p className="scan-tip">
                      请使用 <Text strong>企业微信</Text> 扫一扫登录
                    </p>
                    
                    <Divider plain>扫码后验证</Divider>

                    <Form 
                      form={scanForm} 
                      onFinish={handleScanLogin} 
                      style={{ width: '100%' }}
                      size="large"
                    >
                      <Form.Item
                        name="dynamicCode"
                        rules={[{ required: true, message: '请输入动态验证码' }]}
                      >
                        <Input 
                          prefix={<MobileOutlined />} 
                          placeholder="请输入手机/动态验证码" 
                          suffix={
                            <Button type="link" size="small" style={{ padding: 0 }}>
                              获取验证码
                            </Button>
                          }
                        />
                      </Form.Item>
                      <Button type="primary" htmlType="submit" block loading={loginLoading}>
                        验证并登录
                      </Button>
                    </Form>
                  </div>
                )
              }
            ]}
          />
        </div>
      </div>

      {/* Tenant Selection Modal */}
      <Modal
        title="选择进入的企业"
        open={tenantModalOpen}
        footer={null}
        closable={false}
        centered
        width={480}
      >
        <div style={{ padding: '16px 0' }}>
          <Paragraph type="secondary">
            检测到您的账号关联了多个企业实体，请选择本次登录要进入的企业环境。
          </Paragraph>
          <List
            itemLayout="horizontal"
            dataSource={tenants}
            renderItem={(item: any) => (
              <List.Item>
                <Card 
                  className={`tenant-card ${currentTenant?.id === item.id ? 'selected' : ''}`}
                  style={{ width: '100%' }}
                  bodyStyle={{ padding: '16px' }}
                  onClick={() => handleTenantSelect(item)}
                >
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                      <Avatar shape="square" size="large" src={item.logo} icon={<GlobalOutlined />} />
                      <div>
                        <Text strong style={{ fontSize: 16, display: 'block' }}>{item.name}</Text>
                        <Text type="secondary" style={{ fontSize: 12 }}>ID: {item.id}</Text>
                      </div>
                    </div>
                    <RightOutlined style={{ color: '#bfbfbf' }} />
                  </div>
                </Card>
              </List.Item>
            )}
          />
        </div>
      </Modal>
    </div>
  );
});

export default Component;
