import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Input, Text, View } from '@tarojs/components';
import { getTenantContext } from '@/services/api';
import { loadCurrentUser, sendSmsCode, verifySmsCode } from '@/services/auth';
import '../student.css';

export default function StudentLoginPage() {
  const tenant = getTenantContext();
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [debugCode, setDebugCode] = useState('');
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [sending, setSending] = useState(false);
  const [verifying, setVerifying] = useState(false);

  useEffect(() => {
    loadCurrentUser()
      .then(() => Taro.redirectTo({ url: '/pages/student/home/index' }))
      .catch(() => undefined);
  }, []);

  async function handleSendCode() {
    setSending(true);
    setError('');
    setMessage('');
    try {
      const result = await sendSmsCode(phone);
      const nextCode = typeof result.debugCode === 'string' ? result.debugCode : '';
      setDebugCode(nextCode);
      setMessage(nextCode ? `验证码已发送，开发环境验证码 ${nextCode}` : '验证码已发送');
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '验证码发送失败');
    } finally {
      setSending(false);
    }
  }

  async function handleLogin() {
    setVerifying(true);
    setError('');
    try {
      await verifySmsCode(phone, code || debugCode);
      Taro.redirectTo({ url: '/pages/student/home/index' });
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '登录失败');
    } finally {
      setVerifying(false);
    }
  }

  return (
    <View className='student-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>{tenant?.branding.shortName || tenant?.branding.brandName || '题库系统'}</Text>
          <Text className='student-title'>手机号登录</Text>
          <Text className='student-subtitle'>短信登录会由后端校验租户、验证码、会话和用户身份。</Text>
        </View>
      </View>

      <View className='list-stack'>
        <Input className='input' type='number' maxlength={11} placeholder='请输入手机号' value={phone} onInput={event => setPhone(String(event.detail.value || ''))} />
        <View className='toolbar'>
          <Input className='input' type='number' maxlength={6} placeholder='验证码' value={code} onInput={event => setCode(String(event.detail.value || ''))} />
          <Button className='secondary-button' loading={sending} onClick={handleSendCode}>
            发送
          </Button>
        </View>
        <Button className='primary-button' loading={verifying} onClick={handleLogin}>
          登录
        </Button>
        {message ? <Text className='success-text'>{message}</Text> : null}
        {error ? <Text className='error-text'>{error}</Text> : null}
      </View>
    </View>
  );
}
