import { useState } from 'react'
import { Link } from 'react-router-dom'
import { Eye, EyeOff } from 'lucide-react'
import Logo from '../../components/ui/Logo'
import { authApi } from '../../lib/api-services'
import { Input, Label } from '../../components/ui/Input'
import Button from '../../components/ui/Button'

export default function ForgotPassword() {
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)
  const [loading, setLoading] = useState(false)
  const [step, setStep] = useState<1 | 2>(1)
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [sentCode, setSentCode] = useState('')

  const sendCode = async () => {
    setError('')
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      setError('手机号格式不正确')
      return
    }
    setLoading(true)
    try {
      const res = await authApi.forgotPasswordSendCode(phone) as any
      setSentCode(res?.code || '')
      setStep(2)
    } catch (err: any) {
      setError(err.response?.data?.error?.message || '发送失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const resetPwd = async () => {
    setError('')
    if (code.length !== 6) {
      setError('请输入6位验证码')
      return
    }
    if (newPassword.length < 8) {
      setError('密码至少8位')
      return
    }
    setLoading(true)
    try {
      await authApi.forgotPasswordVerify({ phone, code, newPassword })
      setSuccess(true)
    } catch (err: any) {
      setError(err.response?.data?.error?.message || '重置失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-surface px-4">
      <div className="w-full max-w-sm">
        <div className="flex items-center justify-center gap-2 mb-8">
          <Logo className="w-8 h-8 object-contain" />
          <span className="text-xl font-bold">安职通</span>
        </div>

        <div className="card">
          <h1 className="text-lg font-semibold mb-4">重置密码</h1>

          {success ? (
            <div className="text-center py-4">
              <div className="text-green-600 mb-3">密码已重置成功</div>
              <Link to="/login" className="text-primary hover:underline text-sm">返回登录</Link>
            </div>
          ) : (
            <>
              {error && (
                <div className="mb-4 px-3 py-2 rounded-md bg-red-50 text-red-700 text-sm">{error}</div>
              )}

              {sentCode && step === 2 && (
                <div className="mb-4 px-3 py-2 rounded-md bg-blue-50 text-blue-700 text-sm">
                  验证码：{sentCode}（开发阶段直接显示，生产环境将发送短信）
                </div>
              )}

              {step === 1 ? (
                <div className="space-y-4">
                  <div>
                    <Label>手机号</Label>
                    <Input
                      type="tel"
                      placeholder="请输入注册手机号"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      maxLength={11}
                    />
                  </div>
                  <Button className="w-full" disabled={loading} onClick={sendCode}>
                    {loading ? '发送中...' : '获取验证码'}
                  </Button>
                </div>
              ) : (
                <div className="space-y-4">
                  <div>
                    <Label>手机号</Label>
                    <Input type="tel" value={phone} disabled />
                  </div>
                  <div>
                    <Label>验证码</Label>
                    <Input
                      type="text"
                      placeholder="6位验证码"
                      value={code}
                      onChange={(e) => setCode(e.target.value)}
                      maxLength={6}
                    />
                  </div>
                  <div>
                    <Label>新密码</Label>
                    <div className="relative">
                      <Input
                        type={showPassword ? 'text' : 'password'}
                        placeholder="至少8位"
                        value={newPassword}
                        onChange={(e) => setNewPassword(e.target.value)}
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400"
                      >
                        {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                  <Button className="w-full" disabled={loading} onClick={resetPwd}>
                    {loading ? '重置中...' : '重置密码'}
                  </Button>
                  <button
                    className="w-full text-xs text-gray-500 hover:text-gray-700"
                    onClick={() => { setStep(1); setCode(''); setSentCode('') }}
                  >
                    重新获取验证码
                  </button>
                </div>
              )}

              <div className="mt-4 text-center text-sm">
                <Link to="/login" className="text-primary hover:underline">返回登录</Link>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
