/**
 * H5 登录页
 * 手机号 + 密码登录，支持重定向到目标页面
 */
import { useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useH5AuthStore } from '../auth';

export default function H5Login() {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const { login, loading } = useH5AuthStore();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const redirect = searchParams.get('redirect') || '/pms';

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (!phone || !password) {
      setError('请输入手机号和密码');
      return;
    }
    try {
      await login(phone, password);
      navigate(redirect, { replace: true });
    } catch (err) {
      setError((err as Error).message);
    }
  };

  return (
    <div className="flex min-h-screen flex-col bg-white px-6">
      {/* 顶部品牌区 */}
      <div className="mt-20 mb-12 text-center">
        <div className="mx-auto mb-3 flex h-16 w-16 items-center justify-center rounded-2xl bg-blue-600 text-2xl text-white font-bold">
          P
        </div>
        <h1 className="text-xl font-bold text-gray-900">安知充</h1>
        <p className="mt-1 text-sm text-gray-500">充电柜管理系统</p>
      </div>

      {/* 登录表单 */}
      <form onSubmit={handleSubmit} className="flex flex-col gap-4">
        <div>
          <input
            className="w-full rounded-lg border border-gray-300 px-4 py-3 text-base outline-none focus:border-blue-500"
            type="tel"
            placeholder="手机号"
            maxLength={11}
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            autoComplete="tel"
          />
        </div>
        <div>
          <input
            className="w-full rounded-lg border border-gray-300 px-4 py-3 text-base outline-none focus:border-blue-500"
            type="password"
            placeholder="密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
          />
        </div>

        {error && <p className="text-center text-sm text-red-500">{error}</p>}

        <button
          type="submit"
          disabled={loading}
          className="mt-2 w-full rounded-lg bg-blue-600 py-3 text-base font-medium text-white disabled:opacity-50"
        >
          {loading ? '登录中...' : '登录'}
        </button>
      </form>
    </div>
  );
}
