import { useState } from "react"
import {
  AuditOutlined,
  CloudServerOutlined,
  DatabaseOutlined,
  LockOutlined,
  LoginOutlined,
  SafetyCertificateOutlined,
  ThunderboltOutlined,
  UserOutlined,
} from "@ant-design/icons"
import { Alert, Button, Card, Col, Divider, Form, Input, Layout, Row, Space, Steps, Tag, Typography, theme } from "antd"
import { useAdminAuth } from "../contexts/AdminAuthContext"
import { verifyCaptcha } from "../../utils/geetest"
import { toast } from "../../utils/toast"

const { Content } = Layout
const { Title, Text, Paragraph } = Typography

type LoginForm = {
  account: string
  password: string
}

const featureItems = [
  { icon: <CloudServerOutlined />, title: "资源管理", desc: "统一管理云服务器、产品、订单与财务数据" },
  { icon: <DatabaseOutlined />, title: "数据审计", desc: "关键操作保留记录，便于追踪和核对" },
  { icon: <ThunderboltOutlined />, title: "运营效率", desc: "集中处理开通、续费、充值和用户问题" },
]

export default function AdminLogin() {
  const { token } = theme.useToken()
  const { login } = useAdminAuth()
  const [submitting, setSubmitting] = useState(false)

  const handleFinish = async (values: LoginForm) => {
    setSubmitting(true)
    try {
      const captcha = await verifyCaptcha()
      await login(values.account, values.password, captcha)
      toast.success("登录成功")
    } catch (err: unknown) {
      const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || (err instanceof Error ? err.message : "登录失败"))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Layout style={{ minHeight: "100vh", background: token.colorBgLayout }}>
      <Content style={{ padding: 24, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Row gutter={[24, 24]} align="middle" style={{ width: "100%", maxWidth: 1120 }}>
          <Col xs={24} lg={14}>
            <Space orientation="vertical" size={22} style={{ width: "100%" }}>
              <Space orientation="vertical" size={12}>
                <Tag color="blue" icon={<SafetyCertificateOutlined />}>Admin Console</Tag>
                <Title level={1} style={{ margin: 0 }}>管理后台</Title>
                <Paragraph type="secondary" style={{ maxWidth: 560, margin: 0, fontSize: 16 }}>
                  面向运营和管理人员的控制台入口，用于处理用户、产品、订单、财务和云资源管理。
                </Paragraph>
              </Space>

              <Row gutter={[16, 16]}>
                {featureItems.map((item) => (
                  <Col xs={24} sm={8} key={item.title}>
                    <Card variant="outlined" styles={{ body: { minHeight: 132 } }}>
                      <Space orientation="vertical" size={10}>
                        <Text style={{ color: token.colorPrimary, fontSize: 22 }}>{item.icon}</Text>
                        <Text strong>{item.title}</Text>
                        <Text type="secondary" style={{ fontSize: 13 }}>{item.desc}</Text>
                      </Space>
                    </Card>
                  </Col>
                ))}
              </Row>

              <Card variant="outlined">
                <Steps
                  current={1}
                  items={[
                    { title: "身份验证", icon: <UserOutlined /> },
                    { title: "安全校验", icon: <LockOutlined /> },
                    { title: "操作审计", icon: <AuditOutlined /> },
                  ]}
                />
              </Card>
            </Space>
          </Col>

          <Col xs={24} lg={10}>
            <Card
              variant="outlined"
              styles={{ body: { padding: 28 } }}
              title={
                <Space>
                  <SafetyCertificateOutlined />
                  管理员登录
                </Space>
              }
            >
              <Space orientation="vertical" size={18} style={{ width: "100%" }}>
                <Alert
                  type="info"
                  showIcon
                  title="受保护的后台入口"
                  description="请使用管理员账户登录，登录前会进行安全验证。"
                />

                <Form<LoginForm>
                  layout="vertical"
                  requiredMark={false}
                  onFinish={handleFinish}
                  disabled={submitting}
                >
                  <Form.Item
                    label="账号"
                    name="account"
                    rules={[{ required: true, message: "请输入账号" }]}
                  >
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="用户名 / 邮箱 / 手机号"
                      autoComplete="username"
                      size="large"
                    />
                  </Form.Item>

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

                  <Button
                    type="primary"
                    htmlType="submit"
                    block
                    size="large"
                    icon={<LoginOutlined />}
                    loading={submitting}
                  >
                    登录后台
                  </Button>
                </Form>

                <Divider style={{ margin: 0 }} />

                <Space style={{ width: "100%", justifyContent: "center" }}>
                  <AuditOutlined />
                  <Text type="secondary">所有登录记录将被审计</Text>
                </Space>
              </Space>
            </Card>
          </Col>
        </Row>
      </Content>
    </Layout>
  )
}
