import {
  GiftOutlined,
  GlobalOutlined,
  LockOutlined,
  MobileOutlined,
  SafetyCertificateOutlined,
  ThunderboltOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { App, Button, Form, Input, Space, Tabs } from 'antd'
import { useEffect, useState } from 'react'
import { Navigate, useNavigate } from 'react-router'

import { loginWorker, registerWorker, sendWorkerSmsCode } from '@/services/worker'
import { hasWorkerSession, setWorkerSession } from '@/utils/worker-auth'

const SMS_COUNTDOWN_SECONDS = 60

const brandFeatures = [
  {
    icon: <ThunderboltOutlined />,
    title: '实时派单',
    desc: '新单自动刷新，空闲时优先看大厅',
  },
  {
    icon: <SafetyCertificateOutlined />,
    title: '押金保障',
    desc: '接单冻结押金，验收后按规则释放',
  },
  {
    icon: <GiftOutlined />,
    title: '结算清晰',
    desc: '订单收益、冻结与提现记录统一查看',
  },
]

export default function WorkerLoginPage() {
  const navigate = useNavigate()
  const { message } = App.useApp()
  const [loading, setLoading] = useState(false)
  const [registerForm] = Form.useForm()
  const [countdown, setCountdown] = useState(0)

  useEffect(() => {
    if (countdown <= 0) return
    const timer = window.setInterval(() => setCountdown((value) => value - 1), 1000)
    return () => window.clearInterval(timer)
  }, [countdown])

  if (hasWorkerSession()) {
    return <Navigate to="/worker/hall" replace />
  }

  async function submitLogin(values: { username: string; password: string }) {
    setLoading(true)
    try {
      const response = await loginWorker(values)
      setWorkerSession(response.data.token, response.data.expiresAt, response.data.worker)
      message.success('登录成功')
      navigate('/worker/hall', { replace: true })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '登录失败')
    } finally {
      setLoading(false)
    }
  }

  async function requestSmsCode() {
    const phone = String(registerForm.getFieldValue('phone') || '').trim()
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      message.error('请先填写正确的手机号')
      return
    }
    setLoading(true)
    try {
      const response = await sendWorkerSmsCode({ phone })
      setCountdown(SMS_COUNTDOWN_SECONDS)
      message.success(
        response.data.provider === 'mock'
          ? '验证码已发送（开发模式，验证码见服务日志）'
          : `验证码已发送，${response.data.expiresInSeconds} 秒内有效`,
      )
    } catch (error) {
      message.error(error instanceof Error ? error.message : '验证码发送失败')
    } finally {
      setLoading(false)
    }
  }

  async function submitRegister(values: {
    phone: string
    code: string
    password: string
    displayName: string
    inviteCode?: string
  }) {
    setLoading(true)
    try {
      await registerWorker(values)
      message.success('注册成功，请使用手机号登录')
      registerForm.resetFields()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '注册失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <main className="auth-page">
      <div className="auth-shell">
        {/* 品牌信息区：移动端隐藏 */}
        <aside className="auth-brand">
          <div className="auth-brand-top">
            <div className="auth-brand-logo">
              <span className="auth-logo-mark">
                <GlobalOutlined />
              </span>
              <div>
                <strong>王大锤</strong>
                <span>接单平台</span>
              </div>
            </div>

            <div className="auth-brand-body">
              <span className="auth-brand-kicker">打手工作台</span>
              <h2>抢单、履约、结算，都在一个入口</h2>
              <p>手机号注册后即可进入大厅，按分类筛单，接单后提交履约结果并等待验收结算。</p>
            </div>
          </div>

          <div className="auth-brand-features">
            {brandFeatures.map((item) => (
              <div className="auth-brand-feature" key={item.title}>
                <span className="auth-feature-icon">{item.icon}</span>
                <div className="auth-brand-feature-text">
                  <strong>{item.title}</strong>
                  <span>{item.desc}</span>
                </div>
              </div>
            ))}
          </div>

          <div className="auth-brand-footer">© {new Date().getFullYear()} 王大锤 · 保留所有权利</div>
        </aside>

        {/* 登录注册表单区 */}
        <section className="auth-form-side">
          <div className="auth-form-card">
            {/* 移动端精简品牌栏 */}
            <div className="auth-mobile-brand">
              <span className="auth-logo-mark">
                <GlobalOutlined />
              </span>
              <strong>王大锤 · 接单平台</strong>
            </div>

            <Tabs
              centered
              size="large"
              defaultActiveKey="login"
              items={[
                {
                  key: 'login',
                  label: '登录',
                  children: (
                    <>
                      <div className="auth-form-header">
                        <h1>欢迎回来</h1>
                        <p>使用账号或手机号登录，进入抢单大厅</p>
                      </div>
                      <Form layout="vertical" onFinish={submitLogin} requiredMark={false}>
                        <Form.Item
                          label="账号 / 手机号"
                          name="username"
                          rules={[{ required: true, message: '请输入账号或手机号' }]}
                        >
                          <Input prefix={<UserOutlined />} autoComplete="username" />
                        </Form.Item>
                        <Form.Item
                          label="密码"
                          name="password"
                          rules={[{ required: true, message: '请输入密码' }]}
                        >
                          <Input.Password
                            prefix={<LockOutlined />}
                            autoComplete="current-password"
                          />
                        </Form.Item>
                        <Button
                          type="primary"
                          htmlType="submit"
                          loading={loading}
                          size="large"
                          block
                        >
                          登录
                        </Button>
                      </Form>
                    </>
                  ),
                },
                {
                  key: 'register',
                  label: '注册',
                  children: (
                    <>
                      <div className="auth-form-header">
                        <h1>创建账号</h1>
                        <p>手机号验证码注册，注册后即可开始接单</p>
                      </div>
                      <Form
                        form={registerForm}
                        layout="vertical"
                        onFinish={submitRegister}
                        requiredMark={false}
                      >
                        <Form.Item
                          label="手机号"
                          name="phone"
                          rules={[
                            { required: true, message: '请输入手机号' },
                            {
                              pattern: /^1[3-9]\d{9}$/,
                              message: '手机号格式不正确',
                            },
                          ]}
                        >
                          <Input prefix={<MobileOutlined />} autoComplete="tel" maxLength={11} />
                        </Form.Item>
                        <Form.Item
                          label="短信验证码"
                          name="code"
                          rules={[{ required: true, message: '请输入短信验证码' }]}
                        >
                          <Space.Compact style={{ width: '100%' }}>
                            <Input
                              prefix={<SafetyCertificateOutlined />}
                              placeholder="6 位数字验证码"
                              maxLength={6}
                            />
                            <Button
                              loading={loading}
                              disabled={countdown > 0}
                              onClick={requestSmsCode}
                            >
                              {countdown > 0 ? `${countdown}s 后重发` : '获取验证码'}
                            </Button>
                          </Space.Compact>
                        </Form.Item>
                        <Form.Item
                          label="昵称"
                          name="displayName"
                          rules={[{ required: true, message: '请输入昵称' }]}
                        >
                          <Input prefix={<UserOutlined />} />
                        </Form.Item>
                        <Form.Item label="邀请码（选填）" name="inviteCode">
                          <Input
                            prefix={<GiftOutlined />}
                            maxLength={8}
                            placeholder="填写邀请人邀请码"
                          />
                        </Form.Item>
                        <Form.Item
                          label="密码"
                          name="password"
                          rules={[
                            {
                              required: true,
                              min: 6,
                              message: '密码至少 6 位',
                            },
                          ]}
                        >
                          <Input.Password prefix={<LockOutlined />} autoComplete="new-password" />
                        </Form.Item>
                        <Button
                          type="primary"
                          htmlType="submit"
                          loading={loading}
                          size="large"
                          block
                        >
                          注册
                        </Button>
                      </Form>
                    </>
                  ),
                },
              ]}
            />

            <div className="auth-form-footer">注册即代表同意平台《服务协议》与《隐私政策》</div>
          </div>
        </section>
      </div>
    </main>
  )
}
