import { useState, useEffect } from 'react';
import { useNavigate, Form } from '@remix-run/react';
import { type MetaFunction, type ActionFunctionArgs, LoaderFunctionArgs, redirect, json } from "@remix-run/node";
import styles from "~/styles/pages/home.css?url";
import { getUserSession, logout } from "~/root";

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

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

// 处理登出请求
export async function action({ request }: ActionFunctionArgs) {
  const formData = await request.formData();
  const intent = formData.get("intent");
  
  if (intent === "logout") {
    return logout(request);
  }
  
  return null;
}

// 验证用户登录状态
export async function loader({ request }: LoaderFunctionArgs) {
  const { isAuthenticated } = await getUserSession(request);
  
  if (!isAuthenticated) {
    return redirect("/login");
  }
  
  return json({ isAuthenticated });
}

export default function Home() {
  const navigate = useNavigate();
  const [currentTime, setCurrentTime] = useState('');
  const [currentDate, setCurrentDate] = useState('');
  
  // 更新日期时间
  useEffect(() => {
    const updateDateTime = () => {
      const now = new Date();
      // 格式化日期: YYYY/MM/DD
      const date = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '/');
      
      // 格式化时间: HH:MM
      const time = now.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      });
      
      setCurrentDate(date);
      setCurrentTime(time);
    };
    
    // 初始化时间
    updateDateTime();
    
    // 每分钟更新一次
    const interval = setInterval(updateDateTime, 60000);
    
    return () => clearInterval(interval);
  }, []);
  
  // 处理模块点击
  const handleModuleClick = (path: string) => {
    navigate(path);
  };

  // 处理键盘事件
  const handleKeyDown = (path: string, e: React.KeyboardEvent<HTMLDivElement>) => {
    if (e.key === 'Enter' || e.key === ' ') {
      handleModuleClick(path);
    }
  };

  // 处理登出
  const handleLogout = () => {
    // 使用Form组件提交登出请求
    const form = document.getElementById('logout-form') as HTMLFormElement;
    if (form) {
      form.submit();
    }
  };

  return (
    <div className="home-page">
      {/* 登出表单 - 隐藏 */}
      <Form method="post" id="logout-form" className="hidden">
        <input type="hidden" name="intent" value="logout" />
      </Form>
      
      {/* 头部 */}
      <header className="header">
        <div className="logo-container">
          <img src="/logo.png" alt="中国烟草" className="logo" />
          <span className="logo-text">中国烟草</span>
          <span className="logo-text-en">CHINA TOBACCO</span>
        </div>
        <div className="user-info">
          <span className="datetime">{currentDate} {currentTime}</span>
          <div className="user">
            <img src="/avatar.png" alt="用户头像" className="avatar" />
            <span className="username">系统管理员</span>
            <button 
              onClick={handleLogout} 
              className="logout-button"
              aria-label="登出"
            >
              <i className="ri-logout-box-line"></i>
            </button>
          </div>
        </div>
      </header>
      
      {/* 主要内容 */}
      <main className="main-content">
        <h1 className="welcome-text">- 欢迎来到智慧法务平台 -</h1>
        
        <div className="modules-container">
          {/* 合同管理模块 */}
          <div 
            className="module-card" 
            onClick={() => handleModuleClick('/documents')}
            onKeyDown={(e) => handleKeyDown('/documents', e)}
            role="button"
            tabIndex={0}
            aria-label="合同管理"
          >
            <div className="module-icon contract-icon"></div>
            <span className="module-name">合同管理</span>
          </div>
          
          {/* 案卷智能评查模块 */}
          <div 
            className="module-card" 
            onClick={() => handleModuleClick('/')}
            onKeyDown={(e) => handleKeyDown('/', e)}
            role="button"
            tabIndex={0}
            aria-label="案卷智能评查"
          >
            <div className="module-icon review-icon"></div>
            <span className="module-name">案卷智能评查</span>
          </div>
          
          {/* 智慧法务大模型模块 */}
          <div 
            className="module-card" 
            onClick={() => handleModuleClick('/prompts')}
            onKeyDown={(e) => handleKeyDown('/prompts', e)}
            role="button"
            tabIndex={0}
            aria-label="智慧法务大模型"
          >
            <div className="module-icon ai-icon"></div>
            <span className="module-name">智慧法务大模型</span>
          </div>
        </div>
      </main>
      
      {/* 底部山水背景 */}
      <footer className="footer">
        <div className="mountains-bg"></div>
      </footer>
    </div>
  );
} 