import { JsonCard } from "@/components/cards/JsonCard";
import { UserCard } from "@/components/cards/UserCard";
import { EmailClassificationCard } from "@/components/cards/authifier/EmailClassificationCard";
import { NavigationToolbar } from "@/components/common/NavigationToolbar";
import { AccountActions } from "@/components/pages/inspector/AccountActions";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  fetchAccountById,
  fetchSessionsByAccount,
  fetchUserById,
} from "@/lib/db";
import dayjs from "dayjs";
import { notFound } from "next/navigation";
import { User } from "revolt-api";
import { decodeTime } from "ulid";

import relativeTime from "dayjs/plugin/relativeTime";
import SafetyNotesCard from "@/components/cards/SafetyNotesCard";
dayjs.extend(relativeTime);

export default async function User({
  params,
}: {
  params: { id: string; type: string };
}) {
  const account = await fetchAccountById(params.id);
  if (!account) return notFound();

  const user = await fetchUserById(params.id);
  const sessions = await fetchSessionsByAccount(params.id).catch(() => []);

  return (
    <div className="flex flex-col gap-2">
      <NavigationToolbar>Inspecting Account</NavigationToolbar>
      {user && <UserCard user={user} subtitle={account.email} withLink />}
      <AccountActions account={account} user={user as User} />
      <EmailClassificationCard email={account.email} />
      <SafetyNotesCard objectId={account._id} type="account" />

      <Separator />
      <Card>
        <CardHeader>
          <CardTitle>Active Sessions</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Created</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sessions.map((session) => (
                <TableRow key={session._id}>
                  <TableCell>{session.name}</TableCell>
                  <TableCell>
                    {dayjs(decodeTime(session._id)).fromNow()}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Separator />
      <JsonCard obj={account} />

      {/*TODO? update password, reset 2FA, disable / undisable (disabled if pending
      delete), delete / cancel delete
      <br />
      list active 2FA methods without keys
      <br />
      email account*/}
    </div>
  );
}
