import { A, useNavigate, useParams } from "@solidjs/router";
import { createSignal, onMount, Show } from "solid-js";

import { authClient } from "~/lib/auth-client";
import { useApp } from "~/lib/app-context";
import type { Invite } from "~/lib/types";

export default function AcceptInvitePage() {
  const params = useParams();
  const navigate = useNavigate();
  const app = useApp();
  const session = authClient.useSession();
  const [accepted, setAccepted] = createSignal(false);
  const [invite, setInvite] = createSignal<Invite | null>(null);

  onMount(() => {
    const token = params.token;
    if (!token) return;
    
    void app.getInviteByToken(token).then(entry => {
      setInvite(entry);
      if (entry?.status === "accepted") {
        setAccepted(true);
      }
    });
  });

  const accept = async () => {
    const token = params.token;
    if (!token) return;
    
    const success = await app.acceptInvite(token);
    setAccepted(success);
    if (success) {
      navigate(`/app/${app.primaryWorkspace()?.slug ?? "personal"}/settings`);
    }
  };

  return (
    <main class="flex min-h-screen items-center justify-center px-4 py-6">
      <div class="app-surface w-full max-w-xl rounded-[2rem] p-8">
        <p class="section-title">Workspace Invitation</p>
        <h1 class="mt-3 text-3xl font-extrabold tracking-[-0.05em]">Join Personal HQ</h1>
        <Show when={invite()} fallback={<p class="mt-4 text-soft">This invite link is missing or expired.</p>}>
          <p class="mt-4 text-sm leading-7 text-soft">
            {invite()!.email} was invited as a {invite()!.role}. Accept the link after signing in to add the member to the workspace.
          </p>
          <Show when={session().data} fallback={<A href="/login" class="button-primary mt-6 inline-flex px-5 py-3 text-sm">Sign in first</A>}>
            <button class="button-primary mt-6 inline-flex px-5 py-3 text-sm" onClick={() => void accept()}>
              {accepted() ? "Invitation accepted" : "Accept invitation"}
            </button>
          </Show>
        </Show>
      </div>
    </main>
  );
}
