import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import useAuthStore from '../store/authStore';
import api from '../services/api';
import './Login.css';

const Login = () => {
  const [mode, setMode] = useState('login');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const setAuth = useAuthStore((state) => state.setAuth);

  const onLogin = async (values) => {
    setLoading(true);
    try {
      const formData = new URLSearchParams();
      formData.append('username', values.email);
      formData.append('password', values.password);
      const res = await api.post('/users/login', formData);
      const token = res.data.access_token;
      
      // 先保存 token 到 localStorage，这样拦截器就能读取到
      localStorage.setItem('user_token', token);
      
      const userRes = await api.get('/users/me');
      setAuth(userRes.data, token);
      message.success('登录成功');
      navigate('/dashboard');
    } catch (error) {
      console.error('登录错误:', error);
      message.error('登录失败，请检查账号和密码');
      localStorage.removeItem('user_token'); // 清除可能存在的 token
    } finally {
      setLoading(false);
    }
  };

  const onRegister = async (values) => {
    setLoading(true);
    try {
      await api.post('/users/register', {
        username: values.username,
        email: values.email,
        password: values.password,
      });
      message.success('注册成功，请登录');
      setMode('login');
    } catch (e) {
      message.error(e.response?.data?.detail || '注册失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="ux-login-root">
      {/* 左侧品牌区 */}
      <div className="ux-brand">
        <div className="ux-brand-content">
          {/* Logo */}
          <div className="ux-logo">
            <div className="ux-logo-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <span>灵犀智能</span>
          </div>

          {/* 标语 */}
          <div className="ux-brand-headline">
            <h1>智能驱动，<br />沟通无界</h1>
            <p>Editorial Intelligence for the modern architectural era.</p>
          </div>

          {/* 状态卡片 */}
          <div className="ux-stats-grid">
            <div className="ux-stat-card">
              <div className="ux-stat-label">
                <span>系统负载</span>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="rgba(255,255,255,0.7)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <div className="ux-stat-value">14% <span className="ux-stat-tag">正常</span></div>
            </div>
            <div className="ux-stat-card">
              <div className="ux-stat-label">
                <span>响应延迟</span>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <circle cx="12" cy="12" r="10" stroke="rgba(255,255,255,0.7)" strokeWidth="2"/>
                  <path d="M12 6v6l4 2" stroke="rgba(255,255,255,0.7)" strokeWidth="2" strokeLinecap="round"/>
                </svg>
              </div>
              <div className="ux-stat-value">24ms <span className="ux-stat-tag">优秀</span></div>
            </div>
          </div>
          <div className="ux-node-card">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <path d="M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z" stroke="rgba(255,255,255,0.8)" strokeWidth="2"/>
            </svg>
            <div>
              <div className="ux-node-title">所有节点在线</div>
              <div className="ux-node-sub">上次回来：3分钟前</div>
            </div>
          </div>
        </div>

        <div className="ux-brand-footer">SAFE WORK</div>
      </div>

      {/* 右侧表单区 */}
      <div className="ux-form-panel">
        <div className="ux-form-box">
          {mode === 'login' ? (
            <>
              <h2 className="ux-form-title">登录</h2>
              <p className="ux-form-sub">欢迎回来，请输入您的凭据以继续访问。</p>

              <Form name="user-login" onFinish={onLogin} layout="vertical" requiredMark={false}>
                <Form.Item label="账号" name="email" rules={[{ required: true, message: '请输入账号' }]}>
                  <Input
                    placeholder="请输入用户名或邮箱"
                    prefix={
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                        <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2M12 11a4 4 0 100-8 4 4 0 000 8z" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    }
                  />
                </Form.Item>

                <Form.Item
                  label={
                    <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                      <span>密码</span>
                      <button type="button" className="ux-link">忘记密码？</button>
                    </div>
                  }
                  name="password"
                  rules={[{ required: true, message: '请输入密码' }]}
                >
                  <Input.Password
                    placeholder="••••••••"
                    prefix={
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                        <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" fill="#9ca3af"/>
                      </svg>
                    }
                  />
                </Form.Item>

                <Form.Item name="remember" valuePropName="checked">
                  <Checkbox>记住我</Checkbox>
                </Form.Item>

                <Form.Item>
                  <Button type="primary" htmlType="submit" block loading={loading} className="ux-submit-btn">
                    登录控制面板 →
                  </Button>
                </Form.Item>
              </Form>

              <div className="ux-divider"><span>或者通过</span></div>

              <p className="ux-switch-text">
                还没有账号？{' '}
                <button type="button" className="ux-link-blue" onClick={() => setMode('register')}>
                  创建账号
                </button>
              </p>
            </>
          ) : (
            <>
              <h2 className="ux-form-title">创建账号</h2>
              <p className="ux-form-sub">填写以下信息完成注册。</p>

              <Form name="user-register" onFinish={onRegister} layout="vertical" requiredMark={false}>
                <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                  <Input placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item label="邮箱地址" name="email" rules={[{ required: true, type: 'email', message: '请输入有效邮箱' }]}>
                  <Input placeholder="name@example.com" />
                </Form.Item>
                <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
                  <Input.Password placeholder="••••••••" />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit" block loading={loading} className="ux-submit-btn">
                    注册账号
                  </Button>
                </Form.Item>
              </Form>

              <p className="ux-switch-text">
                已有账号？{' '}
                <button type="button" className="ux-link-blue" onClick={() => setMode('login')}>
                  返回登录
                </button>
              </p>
            </>
          )}

          <div className="ux-footer-links">
            <span>使用条款</span>
            <span>隐私政策</span>
            <span>© 2024 灵犀智能</span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
