"use client";

import { useEffect, useState } from "react";

import AppShell from "@/components/AppShell";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { api } from "@/lib/api";

type User = { id: string; username: string };

const UsersPage = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [query, setQuery] = useState("");

  const search = async () => {
    const data = (await api.getUsers(query)) as User[];
    setUsers(data);
  };

  useEffect(() => {
    search().catch(() => null);
  }, []);

  return (
    <AppShell>
      <Card className="border-slate-200/80 shadow-sm">
        <CardHeader className="gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <CardTitle>用户列表</CardTitle>
            <CardDescription>搜索并查看账号信息</CardDescription>
          </div>
          <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
            <Input
              placeholder="搜索用户名"
              value={query}
              onChange={(event) => setQuery(event.target.value)}
            />
            <Button onClick={search}>搜索</Button>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {users.map((user) => (
              <Card key={user.id} className="border-slate-200/70 bg-white/70 shadow-sm">
                <CardContent className="p-4 font-medium text-slate-700">
                  {user.username}
                </CardContent>
              </Card>
            ))}
            {users.length === 0 && (
              <div className="rounded-xl border border-dashed border-slate-200 bg-white/60 p-6 text-center text-sm text-slate-500">
                暂无用户
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </AppShell>
  );
};

export default UsersPage;
