import { getUserTeams } from "@/db/mod.ts";
import { Handlers, PageProps } from "$fresh/server.ts";
import { type ContextState, type PublicUser, type Team } from "@/types.ts";

interface DashboardProps {
  user: PublicUser;
  teams: Team[];
}

export const handler: Handlers<unknown, ContextState> = {
  async GET(_request: Request, context) {
    if (context.state.user?.id) {
      const teams = await getUserTeams(context.state.user) || [];
      return await context.render({ user: context.state.user, teams });
    }
    return await context.render();
  },
};

export default function Page(
  { data }: PageProps<DashboardProps | undefined>,
) {
  if (data) {
    return Dashboard(data);
  } else {
    return LoginRequired();
  }
}

function Dashboard({ teams, user }: DashboardProps) {
  return (
    <>
      <h2 class="text-4xl mb-2">
        Hello, {(user.displayName || user.username).trim()}!
      </h2>
      <h3 class="text-lg">
        Here are your teams:
      </h3>
      <ul>
        {teams.map((team) => (
          <li key={team.id}>
            <a href={`/team/${team.id}`}>{team.displayName}</a>
          </li>
        ))}
      </ul>
    </>
  );
}

function LoginRequired() {
  return <a href="/login">You need to login first!</a>;
}
