'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { setUserInfo, getUserInfo, clearUserInfo } from '@/utils/cookie';

export default function Login() {
  const router = useRouter();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [msg, setMsg] = useState({ text: '', type: '' });
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [currentUser, setCurrentUser] = useState('');

  useEffect(() => {
    const info = getUserInfo();
    if (info?.user) {
      setIsLoggedIn(true);
      setCurrentUser(info.user);
      router.push('/');
    }
  }, [router]);

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    setMsg({ text: '', type: '' });
    if (!username || !password) {
      setMsg({ text: '请输入账号与密码。', type: 'error' });
      return;
    }
    if (username !== 'admin' || password !== 'admin') {
      setMsg({ text: '账号或密码错误（演示：admin / admin）。', type: 'error' });
      return;
    }
    setUserInfo(username);
    setMsg({ text: '登录成功，正在跳转…', type: 'info' });
    setTimeout(() => router.push('/'), 500);
  };

  const handleLogout = () => {
    clearUserInfo();
    setIsLoggedIn(false);
    setCurrentUser('');
    setMsg({ text: '已退出登录。', type: 'info' });
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
      <div className="w-full max-w-md p-8 bg-slate-800/80 backdrop-blur rounded-2xl shadow-2xl border border-slate-700">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">AI 智能体工作台</h1>
          <p className="text-slate-400">登录后开始与 AI 对话</p>
        </div>

        {isLoggedIn ? (
          <div className="text-center space-y-4">
            <p className="text-slate-300">
              当前用户：<span className="text-emerald-400 font-semibold">{currentUser}</span>
            </p>
            <button
              onClick={handleLogout}
              className="w-full py-3 bg-slate-700 hover:bg-slate-600 text-white rounded-lg transition"
            >
              退出登录
            </button>
          </div>
        ) : (
          <form onSubmit={handleLogin} className="space-y-5">
            <div>
              <label className="block text-sm text-slate-400 mb-1">账号</label>
              <input
                type="text"
                value={username}
                onChange={e => setUsername(e.target.value)}
                className="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:border-emerald-400 transition"
                placeholder="admin"
              />
            </div>
            <div>
              <label className="block text-sm text-slate-400 mb-1">密码</label>
              <input
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                className="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:border-emerald-400 transition"
                placeholder="admin"
              />
            </div>
            <button
              type="submit"
              className="w-full py-3 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold rounded-lg transition"
            >
              登 录
            </button>
            <button
              type="button"
              onClick={() => { setUsername('admin'); setPassword('admin'); }}
              className="w-full py-2 text-sm text-slate-400 hover:text-slate-300 transition"
            >
              填充演示账号
            </button>
          </form>
        )}

        {msg.text && (
          <div
            className={`mt-4 p-3 rounded-lg text-sm text-center ${
              msg.type === 'error'
                ? 'bg-red-500/20 text-red-400'
                : 'bg-emerald-500/20 text-emerald-400'
            }`}
          >
            {msg.text}
          </div>
        )}
      </div>
    </div>
  );
}
