import React, { useState } from 'react';
import { Form, Input, Button, message, Checkbox } 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'); // 'login' | 'register'
  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.username);
      formData.append('password', values.password);

      const res = await api.post('/users/login', formData);
      const token = res.data.access_token;

      // 先保存 token 到 localStorage，这样拦截器就能读取到
      localStorage.setItem('admin_token', token);

      const userRes = await api.get('/users/me');

      if (!userRes.data.is_admin) {
        message.error('拒绝访问，仅限管理员。');
        localStorage.removeItem('admin_token'); // 清除 token
        return;
      }

      setAuth(userRes.data, token);
      message.success('管理员登录成功');
      navigate('/dashboard');
    } catch (error) {
      console.error('登录错误:', error);
      message.error('登录失败，请检查账号和密码');
      localStorage.removeItem('admin_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="lx-login-root">
      {/* 左侧品牌区 */}
      <div className="lx-brand">
        <div className="lx-brand-inner">
          <div className="lx-logo">
            <svg width="32" height="32" viewBox="0 0 32 32" fill="none" aria-hidden="true">
              <rect width="32" height="32" rx="8" fill="url(#lg1)" />
              <path d="M8 16 L16 8 L24 16 L16 24 Z" fill="white" opacity="0.9" />
              <circle cx="16" cy="16" r="4" fill="white" />
              <defs>
                <linearGradient id="lg1" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
                  <stop stopColor="#6366f1" />
                  <stop offset="1" stopColor="#8b5cf6" />
                </linearGradient>
              </defs>
            </svg>
            <span className="lx-logo-text">灵犀智能</span>
          </div>

          <div className="lx-brand-headline">
            <h1>智能驱动，<br />沟通无界</h1>
            <p>一站式智能问答客服系统，打造您的专属数字员工。</p>
          </div>

          <div className="lx-status-card">
            <div className="lx-status-header">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z" fill="#6366f1"/>
              </svg>
              <span>系统状态</span>
            </div>
            <div className="lx-status-row">
              <span className="lx-status-dot" />
              <span>核心引擎：运行正常</span>
            </div>
            <div className="lx-status-row">
              <span className="lx-status-label">正在同步</span>
              <span className="lx-status-pct">75%</span>
            </div>
            <div className="lx-progress-track">
              <div className="lx-progress-bar" style={{ width: '75%' }} />
            </div>
          </div>
        </div>

        <p className="lx-copyright">© 2024 灵犀智能 核心企业智能。保留所有权利。</p>
      </div>

      {/* 右侧表单区 */}
      <div className="lx-form-panel">
        <div className="lx-form-box">
          {mode === 'login' ? (
            <>
              <h2 className="lx-form-title">登录控制面板</h2>
              <p className="lx-form-sub">欢迎回来。请输入您的详细信息。</p>

              <Form name="admin-login" onFinish={onLogin} layout="vertical" requiredMark={false}>
                <Form.Item
                  label="邮箱地址"
                  name="username"
                  rules={[{ required: true, message: '请输入管理员账号' }]}
                >
                  <Input
                    placeholder="admin@example.com"
                    prefix={
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                        <path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z" fill="#6b7280"/>
                      </svg>
                    }
                  />
                </Form.Item>

                <Form.Item
                  label="密码"
                  name="password"
                  rules={[{ required: true, message: '请输入密码' }]}
                >
                  <Input.Password
                    placeholder="••••••••"
                    prefix={
                      <svg width="16" height="16" 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="#6b7280"/>
                      </svg>
                    }
                  />
                </Form.Item>

                <div className="lx-form-row">
                  <Checkbox>记住我</Checkbox>
                  <button type="button" className="lx-link">忘记密码？</button>
                </div>

                <Form.Item style={{ marginTop: '24px' }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    block
                    loading={loading}
                    className="lx-submit-btn"
                  >
                    登录控制面板
                  </Button>
                </Form.Item>
              </Form>

              <p className="lx-switch-text">
                初次使用该平台？{' '}
                <button type="button" className="lx-link" onClick={() => setMode('register')}>
                  创建账号
                </button>
              </p>
            </>
          ) : (
            <>
              <h2 className="lx-form-title">创建管理账号</h2>
              <p className="lx-form-sub">填写以下信息完成注册。</p>

              <Form name="admin-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="admin@example.com" />
                </Form.Item>

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

                <Form.Item style={{ marginTop: '24px' }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    block
                    loading={loading}
                    className="lx-submit-btn"
                  >
                    注册账号
                  </Button>
                </Form.Item>
              </Form>

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

export default Login;
