import { useState } from "react";
import { Form, useActionData, useNavigation } from "@remix-run/react";
import { type MetaFunction, type ActionFunctionArgs, redirect, type LoaderFunctionArgs } from "@remix-run/node";
import styles from "~/styles/pages/login.css?url";
import { createUserSession, getUserSession, getSession, type UserRole } from "~/root";

export const links = () => [
  { rel: "stylesheet", href: styles }
];

export const meta: MetaFunction = () => {
  return [
    { title: "中国烟草AI合同及卷宗审核系统 - 登录" },
    { name: "description", content: "中国烟草AI合同及卷宗审核系统登录页面" },
  ];
};

// 处理表单提交的action
export async function action({ request }: ActionFunctionArgs) {
  const formData = await request.formData();
  const username = formData.get("username") as string;
  const password = formData.get("password") as string;
  const userRole = formData.get("userRole") as UserRole || 'common';
  
  // 简单的登录验证，实际应用中应该进行真正的身份验证
  if (!username || !password) {
    return Response.json({ error: "用户名和密码不能为空" });
  }
  
  // 在实际应用中，这里应该是对用户名和密码的验证逻辑
  // 简化起见，我们直接视为登录成功
  
  // 获取session中存储的重定向URL，如果没有则默认到/
  const session = await getSession(request);
  // 查看session中存储的redirectTo值
  const redirectTo = session.get("redirectTo") || "/";
  // console.log("登录后重定向到:", redirectTo);
  
  // 创建登录会话并重定向
  return createUserSession(true, userRole, redirectTo);
}

// 加载器，获取当前会话状态
export async function loader({ request }: LoaderFunctionArgs) {
  const { isAuthenticated } = await getUserSession(request);
  
  // 如果已登录，重定向到首页
  if (isAuthenticated) {
    return redirect("/");
  }
  
  return Response.json({ isAuthenticated });
}

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [userRole, setUserRole] = useState<UserRole>("common");
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  
  // 判断是否正在提交表单
  const isSubmitting = navigation.state === "submitting";

  return (
    <div className="login-page">
      <div className="login-container">
        <div className="login-header">
          {/* <img src="/logo.png" alt="中国烟草" className="login-logo" /> */}
          <h1 className="login-title">中国烟草AI合同及卷宗审核系统</h1>
        </div>
        
        <div className="login-form-container">
          <h2 className="login-subtitle">用户登录</h2>
          <Form method="post" className="login-form">
            {actionData?.error && (
              <div className="error-message">{actionData.error}</div>
            )}
            
            <div className="form-group">
              <label htmlFor="username">用户名</label>
              <input
                type="text"
                id="username"
                name="username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className="form-input"
                placeholder="请输入用户名"
                required
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="password">密码</label>
              <input
                type="password"
                id="password"
                name="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="form-input"
                placeholder="请输入密码"
                required
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="userRole">用户角色</label>
              <select
                id="userRole"
                name="userRole"
                value={userRole}
                onChange={(e) => setUserRole(e.target.value as UserRole)}
                className="form-input"
                required
              >
                <option value="common">普通用户</option>
                {/* <option value="developer">开发者</option> */}
              </select>
            </div>
            
            <button 
              type="submit" 
              className="login-button"
              disabled={isSubmitting}
            >
              {isSubmitting ? "登录中..." : "登录"}
            </button>
          </Form>
        </div>
        
        <div className="login-footer">
          <p>© 2024 中国烟草 版权所有</p>
        </div>
      </div>
    </div>
  );
} 