/**
 * 平台管理员登录页
 * 独立入口 /platform/login，仅 SUPER_ADMIN 角色可登录
 * 支持记住手机号和密码（localStorage）
 */
import { useState, useEffect } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { Eye, EyeOff, Shield } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useAuthStore } from '../../store/authStore'
import { authApi } from '../../lib/api-services'
import { Input, Label } from '../../components/ui/Input'
import Button from '../../components/ui/Button'

const schema = z.object({
  phone: z.string().regex(/^1[3-9]\d{9}$/, '手机号格式不正确'),
  password: z.string().min(1, '请输入密码'),
})

type FormData = z.infer<typeof schema>

const STORAGE_KEY = 'platform-login-remember'

export default function PlatformLogin() {
  const navigate = useNavigate()
  const { setAuth } = useAuthStore()
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const [remember, setRemember] = useState(false)

  const { register, handleSubmit, setValue, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      phone: '13800000000',
      password: 'admin123456',
    },
  })

  // 读取记住的账号密码
  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY)
      if (saved) {
        const { phone, password } = JSON.parse(saved)
        if (phone) setValue('phone', phone)
        if (password) setValue('password', password)
        setRemember(true)
      }
    } catch {
      // 忽略解析错误
    }
  }, [setValue])

  const onSubmit = async (formData: FormData) => {
    setError('')
    setLoading(true)
    try {
      const res = await authApi.platformLogin(formData) as any
      // 登录成功后保存/清除记住的账号密码
      if (remember) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify({ phone: formData.phone, password: formData.password }))
      } else {
        localStorage.removeItem(STORAGE_KEY)
      }
      setAuth(res.user, res.accessToken, res.refreshToken)
      navigate('/platform/dashboard')
    } 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">
          <div className="w-10 h-10 rounded-lg bg-primary flex items-center justify-center">
            <Shield className="w-6 h-6 text-white" />
          </div>
          <div>
            <div className="text-xl font-bold text-gray-900">用工专家平台</div>
            <div className="text-xs text-primary">PLATFORM ADMIN</div>
          </div>
        </div>

        <div className="card p-6">
          <h1 className="text-lg font-semibold text-gray-900 mb-1">平台管理员登录</h1>
          <p className="text-xs text-gray-500 mb-4">超级管理员后台，管理所有企业租户</p>

          {error && (
            <div className="mb-4 px-3 py-2 rounded-md bg-red-50 text-red-700 text-sm">{error}</div>
          )}

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div>
              <Label>手机号</Label>
              <Input
                type="tel"
                placeholder="请输入手机号"
                {...register('phone')}
                maxLength={11}
              />
              {errors.phone && <p className="text-xs text-red-500 mt-1">{errors.phone.message}</p>}
            </div>

            <div>
              <Label>密码</Label>
              <div className="relative">
                <Input
                  type={showPassword ? 'text' : 'password'}
                  placeholder="请输入密码"
                  className="pr-10"
                  {...register('password')}
                />
                <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>
              {errors.password && <p className="text-xs text-red-500 mt-1">{errors.password.message}</p>}
            </div>

            <label className="flex items-center gap-2 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={remember}
                onChange={(e) => setRemember(e.target.checked)}
                className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary focus:ring-offset-0"
              />
              <span className="text-sm text-gray-500">记住账号密码</span>
            </label>

            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? '登录中...' : '登录'}
            </Button>
          </form>

          <div className="mt-4 text-center">
            <Link to="/login" className="text-sm text-gray-500 hover:text-gray-700">← 返回企业登录</Link>
          </div>
        </div>
      </div>
    </div>
  )
}
