import { prisma } from "@streamclipper/db";
import { getSession } from "../../lib/auth";
import { addUser, deleteUser } from "./actions";
import { formatTr } from "../../lib/formatDate";
import { ConfirmButton } from "../components/ConfirmButton";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

export const dynamic = "force-dynamic";

export default async function UsersPage() {
  const [users, session] = await Promise.all([prisma.user.findMany({ orderBy: { createdAt: "asc" } }), getSession()]);

  return (
    <div className="flex flex-col gap-6">
      <h1 className="text-2xl font-semibold tracking-tight">Kullanıcılar</h1>

      <Card>
        <CardContent>
          <form action={addUser} className="flex flex-wrap gap-2">
            <Input name="username" placeholder="Kullanıcı adı" required className="flex-1 min-w-[140px]" />
            <Input
              name="password"
              type="password"
              placeholder="Şifre (en az 8 karakter)"
              required
              minLength={8}
              className="flex-1 min-w-[160px]"
            />
            <Button type="submit">Kullanıcı Ekle</Button>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Kullanıcı Adı</TableHead>
                <TableHead>Oluşturulma</TableHead>
                <TableHead className="text-right"></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {users.map((u) => (
                <TableRow key={u.id}>
                  <TableCell>
                    {u.username}
                    {u.id === session?.sub && (
                      <Badge variant="muted" className="ml-2">
                        sen
                      </Badge>
                    )}
                  </TableCell>
                  <TableCell className="font-mono-num text-xs text-muted-foreground">
                    {formatTr(u.createdAt)}
                  </TableCell>
                  <TableCell className="text-right">
                    {u.id !== session?.sub && users.length > 1 && (
                      <form action={deleteUser.bind(null, u.id)}>
                        <ConfirmButton confirmText={`${u.username} kullanıcısını silmek istediğine emin misin?`} label="Sil" />
                      </form>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
