import { prisma } from "@streamclipper/db";
import { getSession } from "../../lib/auth";
import { addUser, deleteUser } from "./actions";
import { DeleteButton } from "../components/DeleteButton";

export const dynamic = "force-dynamic";

const fieldStyle = {
  background: "var(--bg)",
  border: "1px solid var(--border)",
  borderRadius: "6px",
  padding: "0.5rem 0.7rem",
  color: "var(--text)",
  fontSize: "0.9rem",
};

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

  return (
    <>
      <h1>Kullanıcılar</h1>

      <form
        action={addUser}
        className="card add-channel-form"
        style={{ marginBottom: "1.5rem" }}
      >
        <input name="username" placeholder="Kullanıcı adı" required style={fieldStyle} />
        <input name="password" type="password" placeholder="Şifre (en az 8 karakter)" required minLength={8} style={fieldStyle} />
        <button type="submit">Kullanıcı Ekle</button>
      </form>

      <table>
        <thead>
          <tr>
            <th>Kullanıcı Adı</th>
            <th>Oluşturulma</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {users.map((u) => (
            <tr key={u.id}>
              <td>
                {u.username}
                {u.id === session?.sub && <span className="badge muted" style={{ marginLeft: "0.5rem" }}>sen</span>}
              </td>
              <td className="mono">{u.createdAt.toLocaleString("tr-TR")}</td>
              <td>
                {u.id !== session?.sub && users.length > 1 && (
                  <form action={deleteUser.bind(null, u.id)}>
                    <DeleteButton confirmText={`${u.username} kullanıcısını silmek istediğine emin misin?`} />
                  </form>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}
