import { useState, useEffect } from "react";
import type { MetaFunction, LoaderFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { Button, Card, Typography, Space } from "antd";
import { ClientOnly } from "remix-utils/client-only";
import db from "~/db.server";

const { Title, Paragraph } = Typography;

export const meta: MetaFunction = () => {
  return [
    { title: "Remix 管理系统" },
    { name: "description", content: "欢迎来到 Remix 管理系统！" },
  ];
};

export const loader: LoaderFunction = async () => {
  const userCount = await db("users").count("* as count").first();
  return json({ userCount: userCount?.count || 0 });
};

function WelcomeDemo() {
  const { userCount } = useLoaderData<typeof loader>();
  const [currentTime, setCurrentTime] = useState(new Date());

  useEffect(() => {
    const timer = setInterval(() => setCurrentTime(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);

  return (
    <Card className="w-full max-w-md shadow-lg">
      <Title level={2} className="text-center mb-6">欢迎来到 Remix 管理系统</Title>
      <Paragraph className="text-center mb-4">
        当前时间：{currentTime.toLocaleString()}
      </Paragraph>
      <Paragraph className="text-center mb-6">
        系统中共有 {userCount} 个用户
      </Paragraph>
      <Space direction="vertical" size="middle" className="w-full">
        <Button type="primary" block>
          登录系统
        </Button>
        <Button block>
          查看用户列表
        </Button>
      </Space>
    </Card>
  );
}

export default function Index() {
  return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center">
      <ClientOnly fallback={<p>加载中...</p>}>
        {() => <WelcomeDemo />}
      </ClientOnly>
    </div>
  );
}
