import { useNavigate } from "@solidjs/router";
import { ArrowRight, Mail } from "lucide-solid";
import { createSignal, For, Show } from "solid-js";

import { authBaseUrl, authClient } from "~/lib/auth-client";
import { useApp } from "~/lib/app-context";

type AuthMode = "sign-in" | "sign-up" | "magic-link";

interface DevMailboxEntry {
  id: string;
  kind: "magic-link";
  email: string;
  subject: string;
  url: string;
  createdAt: string;
}

const authModes: Array<{ id: AuthMode; label: string }> = [
  { id: "sign-in", label: "Sign in" },
  { id: "sign-up", label: "Create account" },
  { id: "magic-link", label: "Magic link" }
];

export default function LoginPage() {
  const app = useApp();
  const navigate = useNavigate();
  const devMailboxEnabled = import.meta.env.VITE_DEV_MAILBOX_ENABLED !== "false";
  const [mode, setMode] = createSignal<AuthMode>("sign-in");
  const [name, setName] = createSignal("Taylor");
  const [email, setEmail] = createSignal("taylor@productier.app");
  const [password, setPassword] = createSignal("password1234");
  const [submitting, setSubmitting] = createSignal(false);
  const [error, setError] = createSignal<string | null>(null);
  const [notice, setNotice] = createSignal<string | null>(null);
  const [devMailbox, setDevMailbox] = createSignal<DevMailboxEntry[]>([]);

  const callbackUrl = () => {
    const origin = typeof window !== "undefined" ? window.location.origin : import.meta.env.VITE_FRONTEND_URL || "http://localhost:5173";
    return `${origin}/app/personal/today`;
  };

  const refreshDevMailbox = async () => {
    if (!devMailboxEnabled) {
      return;
    }
    const response = await fetch(`${authBaseUrl}/api/dev-mailbox?email=${encodeURIComponent(email())}`);
    const payload = (await response.json()) as { data?: DevMailboxEntry[] };
    setDevMailbox(payload.data ?? []);
  };

  const openWorkspace = async () => {
    await app.hydrateFromApi().catch(() => undefined);
    navigate("/app/personal/today");
  };

  const submit = async (event: SubmitEvent) => {
    event.preventDefault();
    setSubmitting(true);
    setError(null);
    setNotice(null);

    try {
      if (mode() === "sign-in") {
        const result = await authClient.signIn.email({
          email: email(),
          password: password(),
          rememberMe: true
        });

        if (result.error) {
          setError(result.error.message || "Could not sign in with that email and password.");
          return;
        }

        await openWorkspace();
        return;
      }

      if (mode() === "sign-up") {
        const result = await authClient.signUp.email({
          name: name(),
          email: email(),
          password: password(),
          callbackURL: callbackUrl()
        });

        if (result.error) {
          setError(result.error.message || "Could not create the account.");
          return;
        }

        await openWorkspace();
        return;
      }

      const result = await authClient.signIn.magicLink({
        email: email(),
        name: name().trim() || undefined,
        callbackURL: callbackUrl()
      });

      if (result.error) {
        setError(result.error.message || "Could not send the magic link.");
        return;
      }

      if (devMailboxEnabled) {
        await refreshDevMailbox();
        setNotice("Magic link sent. Check the dev mailbox below.");
      } else {
        setNotice("Magic link sent. Check your inbox for the sign-in link.");
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <main class="flex min-h-screen items-center justify-center p-5" style="position: relative; z-index: 1;">
      <div class="w-full max-w-md">
        {/* Logo */}
        <div class="mb-10 text-center fade-in">
          <div class="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-[var(--accent)] to-[var(--secondary)] text-white text-2xl font-bold shadow-xl">
            P
          </div>
          <h1 class="text-2xl font-semibold mb-2" style="font-family: var(--font-serif);">Productier</h1>
          <p class="text-sm text-[var(--text-muted)]">Calm productivity workspace</p>
        </div>

        {/* Auth card */}
        <div class="rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-8 shadow-xl scale-in">
          {/* Mode tabs */}
          <div class="mb-8 flex rounded-xl bg-[var(--bg-subtle)] p-1.5">
            <For each={authModes}>
              {item => (
                <button
                  class="flex-1 rounded-lg px-4 py-3 text-sm font-semibold transition-all"
                  classList={{
                    "bg-[var(--surface)] text-[var(--text)] shadow-md": mode() === item.id,
                    "text-[var(--text-muted)] hover:text-[var(--text)]": mode() !== item.id
                  }}
                  onClick={() => {
                    setMode(item.id);
                    setError(null);
                    setNotice(null);
                  }}
                >
                  {item.label}
                </button>
              )}
            </For>
          </div>

          {/* Form */}
          <form class="space-y-5" onSubmit={event => void submit(event)}>
            <Show when={mode() !== "sign-in"}>
              <div>
                <label class="mb-2 block text-sm font-semibold">Name</label>
                <input
                  class="input-base"
                  placeholder="Your name"
                  value={name()}
                  onInput={event => setName(event.currentTarget.value)}
                />
              </div>
            </Show>

            <div>
              <label class="mb-2 block text-sm font-semibold">Email</label>
              <input
                class="input-base"
                type="email"
                placeholder="you@example.com"
                value={email()}
                onInput={event => setEmail(event.currentTarget.value)}
              />
            </div>

            <Show when={mode() !== "magic-link"}>
              <div>
                <label class="mb-2 block text-sm font-semibold">Password</label>
                <input
                  class="input-base"
                  type="password"
                  placeholder="••••••••"
                  value={password()}
                  onInput={event => setPassword(event.currentTarget.value)}
                />
                <p class="mt-2 text-xs text-[var(--text-muted)]">
                  Minimum 8 characters. Dev default: password1234
                </p>
              </div>
            </Show>

            <Show when={error()}>
              <div class="rounded-xl bg-[var(--error-muted)] px-5 py-4 text-sm text-[var(--error)] border border-[var(--error)] border-opacity-20">
                {error()}
              </div>
            </Show>

            <Show when={notice()}>
              <div class="rounded-xl bg-[var(--success-muted)] px-5 py-4 text-sm text-[var(--success)] border border-[var(--success)] border-opacity-20">
                {notice()}
              </div>
            </Show>

            <button
              class="button-primary flex w-full items-center justify-center gap-2 px-5 py-3.5 text-base font-semibold"
              disabled={submitting()}
              type="submit"
            >
              <Show when={!submitting()} fallback="Working...">
                {mode() === "sign-in" ? "Sign in" : mode() === "sign-up" ? "Create account" : "Send magic link"}
                <ArrowRight size={18} />
              </Show>
            </button>
          </form>

          {/* Dev mailbox */}
          <Show when={devMailboxEnabled}>
            <div class="mt-8 border-t border-[var(--border)] pt-8">
              <div class="mb-4 flex items-center gap-2">
                <Mail size={16} class="text-[var(--text-muted)]" />
                <span class="text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)]">Dev Mailbox</span>
              </div>

              <button
                class="button-secondary mb-4 w-full px-4 py-2.5 text-sm"
                onClick={() => void refreshDevMailbox()}
                type="button"
              >
                Refresh messages
              </button>

              <div class="space-y-2">
                <Show
                  when={devMailbox().length}
                  fallback={
                    <p class="text-sm text-[var(--text-muted)] text-center py-4">
                      No emails yet. Send a magic link to populate.
                    </p>
                  }
                >
                  <For each={devMailbox()}>
                    {entry => (
                      <a
                        class="block rounded-xl bg-[var(--bg-subtle)] p-4 transition-all hover:bg-[var(--bg-muted)] hover:shadow-sm"
                        href={entry.url}
                      >
                        <div class="flex items-center justify-between gap-2 mb-2">
                          <span class="text-sm font-semibold">{entry.subject}</span>
                          <span class="text-xs text-[var(--text-muted)]">
                            {new Date(entry.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
                          </span>
                        </div>
                        <p class="truncate text-xs text-[var(--text-muted)] font-mono">{entry.url}</p>
                      </a>
                    )}
                  </For>
                </Show>
              </div>
            </div>
          </Show>
        </div>

        {/* Footer */}
        <p class="mt-8 text-center text-xs text-[var(--text-muted)]">
          SolidJS + Vite + Go + PostgreSQL
        </p>
      </div>
    </main>
  );
}
