// ============================================================
// LoginPage — 登录/注册 Modal 弹层
//
// 行为：
//   - 未登录时弹出，不可操作主页（Modal 遮罩）
//   - 可关闭（右上 X），关闭后主页可操作，但 API 401 时会再次弹出
//   - 登录成功 → 关闭 Modal，更新全局登录态
// ============================================================

import { useState, useCallback } from 'react';
import { logger } from '@/shared/utils/bus';
import { Modal, Tabs, Typography, App } from 'antd';

import { useAppContext } from '@/app/providers/AppProvider';
import { useTheme } from '@/app/providers/ThemeProvider';
import { LoginForm } from './components/LoginForm';
import { RegisterForm } from './components/RegisterForm';
import { ForgotPasswordModal } from './components/ForgotPasswordModal';
import { useAuthState } from '../hooks/use-auth-state';
import { AuthAPI, type LoginResponseBody } from '../controllers/auth-api';
import { getDeviceId } from '@/shared/utils/env';
import type { LoginFormValues, RegisterFormValues } from '../model/types';

const { Text } = Typography;

interface LoginPageProps {
   open: boolean;
   onClose: () => void;
}

export function LoginPage({ open, onClose }: LoginPageProps) {
   const { login } = useAppContext();
   const { isDark } = useTheme();
   const { message } = App.useApp();

   const [activeTab, setActiveTab] = useState<string>('login');
   const [submitting, setSubmitting] = useState(false);
   const [forgotOpen, setForgotOpen] = useState(false);

   const authState = useAuthState();

   // ========== 登录 ==========

   const handleLogin = useCallback(
      async (values: LoginFormValues) => {
         setSubmitting(true);
         try {
            const auth: LoginResponseBody = await AuthAPI.login({
               username: values.username,
               password: values.password,
               device_id: getDeviceId(),
               user_ip: '',
            });

            // 记住偏好（用户名、自动登录标记，密码不再持久化）
            authState.saveAuth(values.username, values.password, values.remember, values.autoLogin);

            // 更新全局登录态（内部完成 setToken + emit LOGIN_SUCCESS）
            await login(auth);

            message.success(`登录成功，欢迎 ${auth.display_name || auth.username}`);
            onClose();
         } catch (err) {
            logger.warn('auth', '登录失败', err instanceof Error ? err : undefined);
            message.error((err as Error).message || '登录失败，请检查用户名和密码');
         } finally {
            setSubmitting(false);
         }
      },
      [authState, message, login, onClose],
   );

   // ========== 注册 ==========

   const handleRegister = useCallback(
      async (values: RegisterFormValues) => {
         setSubmitting(true);
         try {
            await AuthAPI.register({
               username: values.username,
               password: values.password,
               phone: values.phone,
               sms_code: values.sms_code,
               device_id: values.device_id || getDeviceId(),
               device_label: values.device_label || '',
               display_name: values.display_name || '',
               referral_code: values.referral_code || '',
            });
            message.success('注册成功，请登录');
            setActiveTab('login');
         } catch (err) {
            logger.warn('auth', '注册失败', err instanceof Error ? err : undefined);
            message.error((err as Error).message || '注册失败');
         } finally {
            setSubmitting(false);
         }
      },
      [message],
   );

   const handleSendSms = useCallback(
      async (phone: string) => {
         try {
            await AuthAPI.sendSms({ phone });
            message.success('验证码已发送');
         } catch (err) {
            logger.warn('auth', '验证码发送失败', err instanceof Error ? err : undefined);
            message.error((err as Error).message || '验证码发送失败');
         }
      },
      [message],
   );

   // ========== 渲染 ==========

   const loginTab = (
      <LoginForm
         initialUsername={authState.username}
         initialRemember={authState.remember}
         initialAutoLogin={authState.autoLogin}
         submitting={submitting}
         onSubmit={handleLogin}
         onRememberChange={authState.handleRememberChange}
         onAutoLoginChange={authState.handleAutoLoginChange}
         onForgotPassword={() => setForgotOpen(true)}
      />
   );

   const registerTab = (
      <RegisterForm submitting={submitting} onSubmit={handleRegister} onSendSms={handleSendSms} />
   );

   return (
      <>
         <Modal
            open={open}
            onCancel={onClose}
            footer={null}
            width={440}
            centered
            destroyOnHidden={false}
            mask={{
               closable: false,
            }}
            styles={{
               body: {
                  padding: '24px 32px 16px',
                  background: isDark ? '#1A1730' : '#FFFFFF',
               },
            }}
         >
            {/* 标题 */}
            <div className="text-center mb-5">
               <Text strong className="text-lg gradient-primary-text block">
                  船长 · HeiXiu
               </Text>
               <Text type="secondary" className="text-xs">
                  欢迎使用船长·HeiXiu
               </Text>
            </div>

            <Tabs
               activeKey={activeTab}
               onChange={setActiveTab}
               centered
               size="small"
               items={[
                  { key: 'login', label: '登录', children: loginTab },
                  { key: 'register', label: '注册', children: registerTab },
               ]}
            />
         </Modal>

         {/* 忘记密码弹窗 */}
         <ForgotPasswordModal open={forgotOpen} onClose={() => setForgotOpen(false)} />
      </>
   );
}
