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

import {
  deleteWorkerSessionWithCredentials,
  loginWorker,
  loginWorkerBySmsCode,
  manageWorkerSessions,
  registerWorker,
  resetWorkerPassword,
  sendWorkerSmsCode,
  sendWorkerPasswordResetSmsCode,
  sendWorkerLoginSmsCode,
} from '@/services/worker'
import type { WorkerSessionDevice } from '@/types/worker-platform'
import { hasWorkerSession, setWorkerSession } from '@/utils/worker-auth'
import { isWorkerPasswordStrong, WORKER_PASSWORD_RULE_MESSAGE } from '@/utils/worker-password'

const SMS_COUNTDOWN_SECONDS = 60
/** 发送失败也冷却一段时间再允许重试，避免连续点击触发服务端每分钟发送次数限制。 */
const SMS_FAILURE_COUNTDOWN_SECONDS = 15

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

export default function WorkerLoginPage() {
  const navigate = useNavigate()
  const { message, modal } = App.useApp()
  const [loading, setLoading] = useState(false)
  const [registerForm] = Form.useForm()
  const [loginSmsForm] = Form.useForm<{ phone: string; code: string }>()
  const loginSmsPhoneInputRef = useRef<InputRef>(null)
  const [resetForm] = Form.useForm<{ phone: string; code: string; password: string }>()
  const [deviceForm] = Form.useForm<{ username: string; password: string }>()
  const [countdown, setCountdown] = useState(0)
  const [loginSmsCountdown, setLoginSmsCountdown] = useState(0)
  const [loginMode, setLoginMode] = useState<'password' | 'sms'>('password')
  const [loginSmsPhone, setLoginSmsPhone] = useState('')
  const [resetCountdown, setResetCountdown] = useState(0)
  const [forgotPasswordOpen, setForgotPasswordOpen] = useState(false)
  const [deviceManagerOpen, setDeviceManagerOpen] = useState(false)
  const [deviceManagerLoading, setDeviceManagerLoading] = useState(false)
  const [managedDevices, setManagedDevices] = useState<WorkerSessionDevice[]>([])

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

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

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

  if (hasWorkerSession()) {
    return <Navigate to="/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)
      if (response.data.passwordWeak) {
        modal.confirm({
          title: '密码安全提醒',
          content: '当前密码强度较弱，为保障账号安全，建议立即修改密码。',
          okText: '去修改密码',
          cancelText: '稍后再说',
          onOk: () => void navigate('/profile', { replace: true }),
          onCancel: () => void navigate('/hall', { replace: true }),
        })
      } else {
        message.success('登录成功')
        void navigate('/hall', { replace: true })
      }
    } catch (error) {
      if (String((error as { errorCode?: string })?.errorCode || '') === 'worker_device_limit') {
        deviceForm.setFieldsValue(values)
        setDeviceManagerOpen(true)
        await loadManagedDevices(values)
        return
      }
      message.error(error instanceof Error ? error.message : '登录失败')
    } finally {
      setLoading(false)
    }
  }

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

  async function submitSmsLogin(values: { phone: string; code: string }) {
    setLoading(true)
    try {
      const response = await loginWorkerBySmsCode({ ...values, phone: getLoginSmsPhone() })
      setWorkerSession(response.data.token, response.data.expiresAt, response.data.worker)
      message.success('登录成功')
      void navigate('/hall', { replace: true })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '验证码登录失败')
    } finally {
      setLoading(false)
    }
  }

  function getLoginSmsPhone() {
    return String(loginSmsPhoneInputRef.current?.input?.value || loginSmsPhone).trim()
  }

  async function loadManagedDevices(values?: { username: string; password: string }) {
    const credentials = values || deviceForm.getFieldsValue()
    if (!credentials.username || !credentials.password) {
      return
    }
    setDeviceManagerLoading(true)
    try {
      const response = await manageWorkerSessions(credentials)
      setManagedDevices(response.data.items)
    } catch (error) {
      message.error(error instanceof Error ? error.message : '读取登录设备失败')
    } finally {
      setDeviceManagerLoading(false)
    }
  }

  async function removeManagedDevice(device: WorkerSessionDevice) {
    const credentials = deviceForm.getFieldsValue()
    setDeviceManagerLoading(true)
    try {
      await deleteWorkerSessionWithCredentials({ ...credentials, sessionId: device.sessionId })
      message.success('登录设备已删除，请重新登录')
      await loadManagedDevices(credentials)
    } catch (error) {
      message.error(error instanceof Error ? error.message : '删除登录设备失败')
    } finally {
      setDeviceManagerLoading(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) {
      setCountdown(SMS_FAILURE_COUNTDOWN_SECONDS)
      message.error(error instanceof Error ? error.message : '验证码发送失败')
    } finally {
      setLoading(false)
    }
  }

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

  async function submitResetPassword(values: { phone: string; code: string; password: string }) {
    setLoading(true)
    try {
      await resetWorkerPassword(values)
      message.success('密码已重置，请使用新密码登录')
      setForgotPasswordOpen(false)
      resetForm.resetFields()
    } 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>
                      <Segmented
                        block
                        value={loginMode}
                        options={[
                          { label: '密码登录', value: 'password' },
                          { label: '验证码登录', value: 'sms' },
                        ]}
                        onChange={(value) => setLoginMode(value as 'password' | 'sms')}
                        style={{ marginBottom: 20 }}
                      />
                      {loginMode === 'password' ? (
                        <Form layout="vertical" onFinish={submitLogin} requiredMark={false}>
                          <Form.Item
                            label="手机号 / 昵称 / 账号"
                            name="username"
                            rules={[{ required: true, message: '请输入手机号、昵称或账号' }]}
                          >
                            <Input
                              prefix={<UserOutlined />}
                              autoComplete="username"
                              placeholder="手机号 / 昵称 / 账号"
                            />
                          </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>
                          <Button
                            type="link"
                            icon={<GlobalOutlined />}
                            block
                            onClick={() => setDeviceManagerOpen(true)}
                          >
                            登录设备管理
                          </Button>
                          <Button type="link" block onClick={() => setForgotPasswordOpen(true)}>
                            忘记密码？
                          </Button>
                        </Form>
                      ) : (
                        <Form
                          form={loginSmsForm}
                          layout="vertical"
                          onFinish={submitSmsLogin}
                          requiredMark={false}
                        >
                          <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[
                              { required: true, message: '请输入手机号' },
                              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
                            ]}
                          >
                            <Input
                              ref={loginSmsPhoneInputRef}
                              prefix={<MobileOutlined />}
                              maxLength={11}
                              placeholder="注册时使用的手机号"
                              value={loginSmsPhone}
                              onChange={(event) => setLoginSmsPhone(event.target.value)}
                            />
                          </Form.Item>
                          <Form.Item label="短信验证码" required>
                            <Space.Compact style={{ width: '100%' }}>
                              <Form.Item
                                name="code"
                                noStyle
                                rules={[{ required: true, message: '请输入短信验证码' }]}
                              >
                                <Input
                                  prefix={<SafetyCertificateOutlined />}
                                  maxLength={6}
                                  placeholder="6 位数字验证码"
                                />
                              </Form.Item>
                              <Button
                                htmlType="button"
                                loading={loading}
                                disabled={loginSmsCountdown > 0}
                                onClick={requestLoginSmsCode}
                              >
                                {loginSmsCountdown > 0
                                  ? `${loginSmsCountdown}s 后重发`
                                  : '获取验证码'}
                              </Button>
                            </Space.Compact>
                          </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: '请输入昵称' }]}
                          extra="昵称需唯一，注册后可作为登录账号使用"
                        >
                          <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,
                              message: '请输入密码',
                            },
                            {
                              validator: (_, value) => {
                                if (!value || isWorkerPasswordStrong(value)) {
                                  return Promise.resolve()
                                }
                                return Promise.reject(new Error(WORKER_PASSWORD_RULE_MESSAGE))
                              },
                            },
                          ]}
                          extra={WORKER_PASSWORD_RULE_MESSAGE}
                        >
                          <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>
      <Modal
        title="忘记密码"
        open={forgotPasswordOpen}
        onCancel={() => {
          setForgotPasswordOpen(false)
          resetForm.resetFields()
        }}
        footer={null}
        destroyOnHidden
      >
        <Form
          form={resetForm}
          layout="vertical"
          onFinish={submitResetPassword}
          requiredMark={false}
        >
          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
            ]}
          >
            <Input prefix={<MobileOutlined />} maxLength={11} placeholder="注册时使用的手机号" />
          </Form.Item>
          <Form.Item
            label="短信验证码"
            name="code"
            rules={[{ required: true, message: '请输入短信验证码' }]}
          >
            <Space.Compact style={{ width: '100%' }}>
              <Input
                prefix={<SafetyCertificateOutlined />}
                maxLength={6}
                placeholder="6 位数字验证码"
              />
              <Button loading={loading} disabled={resetCountdown > 0} onClick={requestResetSmsCode}>
                {resetCountdown > 0 ? `${resetCountdown}s 后重发` : '获取验证码'}
              </Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item
            label="新密码"
            name="password"
            rules={[
              { required: true, message: '请输入新密码' },
              {
                validator: (_, value) =>
                  !value || isWorkerPasswordStrong(value)
                    ? Promise.resolve()
                    : Promise.reject(new Error(WORKER_PASSWORD_RULE_MESSAGE)),
              },
            ]}
            extra={WORKER_PASSWORD_RULE_MESSAGE}
          >
            <Input.Password prefix={<LockOutlined />} autoComplete="new-password" />
          </Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} size="large" block>
            重置密码
          </Button>
        </Form>
      </Modal>

      <Modal
        title="登录设备管理"
        open={deviceManagerOpen}
        width={isMobileViewport() ? '92%' : 720}
        destroyOnHidden
        footer={null}
        onCancel={() => setDeviceManagerOpen(false)}
      >
        <Form
          form={deviceForm}
          layout="vertical"
          onFinish={(values) => void loadManagedDevices(values)}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="username" rules={[{ required: true, message: '请输入账号' }]}>
            <Input prefix={<UserOutlined />} placeholder="手机号 / 昵称 / 账号" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={deviceManagerLoading}>
              查询
            </Button>
          </Form.Item>
        </Form>
        <Alert
          showIcon
          type="info"
          message="验证账号密码后，可删除旧设备。PC 和手机分别最多同时在线 3 台。"
          style={{ marginBottom: 16 }}
        />
        <Table
          size="small"
          rowKey="sessionId"
          loading={deviceManagerLoading}
          dataSource={managedDevices}
          pagination={false}
          columns={[
            {
              title: '设备',
              render: (_, item) => (
                <Space direction="vertical" size={0}>
                  <Typography.Text strong>{item.deviceName || item.deviceType}</Typography.Text>
                  <Typography.Text type="secondary">{item.ipAddress || '未知 IP'}</Typography.Text>
                </Space>
              ),
            },
            {
              title: '最近活动',
              render: (_, item) => item.lastSeenAt.replace('T', ' ').slice(0, 19),
            },
            {
              title: '操作',
              width: 100,
              render: (_, item) => (
                <Button danger type="link" onClick={() => void removeManagedDevice(item)}>
                  删除
                </Button>
              ),
            },
          ]}
        />
      </Modal>
    </main>
  )
}

function isMobileViewport() {
  return typeof window !== 'undefined' && window.innerWidth < 768
}
