import { useState } from 'react'
import { useNavigate, useLocation, Navigate } from 'react-router-dom'
import { useAuth, validateEmail, validatePhone } from '../contexts/AuthContext.jsx'
import { registerOrLogin } from '../services/api.js'
import { PRODUCT } from '../productConfig.js'

export default function Login() {
  const { isAuthed, login } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()
  const from = location.state?.from || '/all-skills'

  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [emailErr, setEmailErr] = useState('')
  const [phoneErr, setPhoneErr] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [agreed, setAgreed] = useState(false)

  if (isAuthed) return <Navigate to={from} replace />

  async function handleSubmit(e) {
    e.preventDefault()
    const eErr = validateEmail(email.trim().toLowerCase())
    const pErr = validatePhone(phone.trim())
    setEmailErr(eErr)
    setPhoneErr(pErr)
    if (eErr || pErr) return
    if (!agreed) {
      alert('请先勾选下方确认项')
      return
    }
    setSubmitting(true)
    try {
      // 1. 本地写入身份凭证
      const u = login(email, phone)
      // 2. 同时通知后端（后端未实现也不阻塞前端流程）
      try { await registerOrLogin({ email: u.email, phone: u.phone }) } catch (_) {}
      navigate(from, { replace: true })
    } catch (err) {
      alert(err.message || '登录失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 flex flex-col lg:flex-row min-h-screen">

      {/* ========== 左侧品牌区 ========== */}
      <div
        className="hidden lg:flex lg:w-1/2 relative overflow-hidden flex-col items-center justify-center px-12"
        style={{ background: 'linear-gradient(160deg, #EEF2FF 0%, #E0E7FF 100%)' }}
      >
        {/* 装饰圆形 */}
        <div className="absolute top-20 left-10 w-32 h-32 rounded-full bg-blue-200/30" />
        <div className="absolute bottom-32 right-16 w-48 h-48 rounded-full bg-indigo-200/20" />
        <div className="absolute top-1/2 left-1/3 w-24 h-24 rounded-full bg-blue-300/20" />
        <div className="absolute top-[15%] right-[20%] w-16 h-16 rounded-full bg-blue-100/40" />

        {/* 品牌内容 */}
        <div className="relative z-10 flex flex-col items-center text-center max-w-md">
          {/* Logo */}
          <div className="w-16 h-16 rounded-2xl bg-blue-600 grid place-items-center mb-6 shadow-lg shadow-blue-600/20">
            <svg viewBox="0 0 32 32" className="w-8 h-8 text-white" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
              <path d="M8 25 L16 7 L24 25" />
              <path d="M11.5 18 L20.5 18" />
              <circle cx="8" cy="25" r="1.6" fill="currentColor" />
              <circle cx="16" cy="7" r="1.6" fill="currentColor" />
              <circle cx="24" cy="25" r="1.6" fill="currentColor" />
            </svg>
          </div>

          {/* 品牌名 */}
          <h1 className="text-3xl font-bold tracking-[0.15em] text-gray-900 mb-4">
            {PRODUCT.shortName}
          </h1>

          {/* 标语 */}
          <p className="text-lg font-medium text-gray-700 mb-2">
            {PRODUCT.subtitle}
          </p>
          <p className="text-sm text-gray-500 leading-relaxed">
            {PRODUCT.fullName}
          </p>
        </div>

        {/* 底部小字 */}
        <p className="absolute bottom-8 text-xs text-gray-400 tracking-wide">
          {PRODUCT.poweredBy}
        </p>
      </div>

      {/* ========== 右侧表单区 ========== */}
      <div className="flex-1 lg:w-1/2 flex flex-col items-center justify-center bg-white px-6 py-10 overflow-y-auto">

        {/* 移动端品牌标识 */}
        <div className="flex lg:hidden items-center gap-2.5 mb-10">
          <div className="w-9 h-9 rounded-xl bg-blue-600 grid place-items-center">
            <svg viewBox="0 0 32 32" className="w-[18px] h-[18px] text-white" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
              <path d="M8 25 L16 7 L24 25" />
              <path d="M11.5 18 L20.5 18" />
              <circle cx="8" cy="25" r="1.6" fill="currentColor" />
              <circle cx="16" cy="7" r="1.6" fill="currentColor" />
              <circle cx="24" cy="25" r="1.6" fill="currentColor" />
            </svg>
          </div>
          <span className="text-base font-bold tracking-[0.12em] text-gray-900">{PRODUCT.shortName}</span>
        </div>

        {/* 表单容器 */}
        <div className="w-full max-w-sm">
          {/* 标题 */}
          <h2 className="text-2xl font-bold text-gray-900">欢迎回来</h2>
          <p className="text-sm text-gray-500 mt-1.5 mb-6">登录或注册你的账号</p>

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* 提示框 */}
            <div className="flex gap-2.5 px-3.5 py-3 rounded-xl bg-blue-50 border border-blue-100">
              <span className="text-blue-500 text-sm mt-0.5 shrink-0">ℹ</span>
              <p className="text-[13px] leading-relaxed text-blue-700">
                邮箱与手机号是你账号的<strong className="font-semibold">唯一身份凭证</strong>，下次登录需使用<strong className="font-semibold">完全一致</strong>的邮箱+手机号。
              </p>
            </div>

            {/* 邮箱 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">邮箱</label>
              <input
                type="email"
                autoComplete="email"
                value={email}
                onChange={e => { setEmail(e.target.value); setEmailErr('') }}
                onBlur={() => setEmailErr(validateEmail(email.trim().toLowerCase()))}
                placeholder="例如：zhangsan@company.com"
                className={[
                  'w-full h-12 px-4 rounded-xl text-sm text-gray-900 bg-white transition-all duration-200 outline-none',
                  'placeholder:text-gray-400',
                  emailErr
                    ? 'border-2 border-red-400 ring-2 ring-red-500/10'
                    : 'border border-gray-200 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400'
                ].join(' ')}
              />
              {emailErr && <p className="text-xs text-red-500 mt-1.5">{emailErr}</p>}
            </div>

            {/* 手机号 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">手机号</label>
              <input
                type="tel"
                inputMode="numeric"
                autoComplete="tel"
                maxLength={11}
                value={phone}
                onChange={e => { setPhone(e.target.value.replace(/\D/g, '')); setPhoneErr('') }}
                onBlur={() => setPhoneErr(validatePhone(phone.trim()))}
                placeholder="11 位中国大陆手机号"
                className={[
                  'w-full h-12 px-4 rounded-xl text-sm text-gray-900 bg-white tracking-wider transition-all duration-200 outline-none',
                  'placeholder:text-gray-400 placeholder:tracking-normal',
                  phoneErr
                    ? 'border-2 border-red-400 ring-2 ring-red-500/10'
                    : 'border border-gray-200 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400'
                ].join(' ')}
              />
              {phoneErr && <p className="text-xs text-red-500 mt-1.5">{phoneErr}</p>}
            </div>

            {/* 确认勾选 */}
            <label className="flex items-start gap-2.5 cursor-pointer select-none pt-1">
              <input
                type="checkbox"
                checked={agreed}
                onChange={e => setAgreed(e.target.checked)}
                className="mt-0.5 w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500/30 cursor-pointer"
              />
              <span className="text-xs leading-relaxed text-gray-500">
                我已确认填写的是<strong className="text-gray-700 font-medium">本人真实邮箱与手机号</strong>，并理解此为账号凭证，下次登录需保持一致。
              </span>
            </label>

            {/* 提交按钮 */}
            <button
              type="submit"
              disabled={submitting || !agreed}
              className={[
                'w-full h-12 rounded-xl text-sm font-semibold transition-all duration-200',
                submitting || !agreed
                  ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                  : 'bg-blue-600 text-white hover:bg-blue-700 active:bg-blue-800 shadow-sm shadow-blue-600/20'
              ].join(' ')}
            >
              {submitting ? (
                <span className="flex items-center justify-center gap-2">
                  <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="3" strokeOpacity="0.3" />
                    <path d="M12 2 a10 10 0 0 1 10 10" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
                  </svg>
                  登录中…
                </span>
              ) : (
                '进入工作区'
              )}
            </button>

            <p className="text-center text-xs text-gray-400 pt-1">
              首次填写将自动注册账号，无需额外步骤
            </p>
          </form>
        </div>
      </div>
    </div>
  )
}
