import { createMemo, createSignal, For, Show } from "solid-js";

import MarkdownPreview from "~/components/markdown-preview";
import { useApp } from "~/lib/app-context";
import { formatStamp } from "~/lib/utils";

export default function NotesRoute() {
  const app = useApp();
  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";
  const notes = createMemo(() => app.state.notes.filter(note => note.workspaceSlug === workspaceSlug()));
  const [selectedId, setSelectedId] = createSignal<string>(notes()[0]?.id ?? "");

  const selected = createMemo(() => notes().find(note => note.id === selectedId()) ?? notes()[0]);
  const selectedSync = createMemo(() => app.noteSyncFor(selected()?.id));
  const syncBadge = createMemo(() => {
    const sync = selectedSync();
    if (!sync) {
      return {
        label: app.online() ? "No local changes" : "Offline",
        detail: app.online() ? "Autosave is ready." : "Changes will queue locally.",
      };
    }

    switch (sync.status) {
      case "saving":
        return { label: "Saving...", detail: sync.message };
      case "synced":
        return { label: "Synced", detail: `${sync.message} • ${formatStamp(sync.updatedAt)}` };
      case "queued":
        return { label: "Queued", detail: sync.message };
      case "error":
        return { label: "Sync issue", detail: sync.message };
      default:
        return { label: "No local changes", detail: "Autosave is ready." };
    }
  });

  const createNote = async () => {
    const note = await app.createNote(workspaceSlug());
    setSelectedId(note.id);
  };

  return (
    <div class="flex h-full gap-4">
      {/* Note list sidebar */}
      <aside class="w-64 shrink-0 rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] p-3">
          <div class="flex items-center justify-between">
            <h1 class="text-sm font-semibold">Notes</h1>
            <button
              class="flex h-7 w-7 items-center justify-center rounded-md text-[var(--text-muted)] transition-colors hover:bg-[var(--bg-subtle)] hover:text-[var(--text)]"
              onClick={() => void createNote()}
              aria-label="New note"
            >
              +
            </button>
          </div>
        </div>
        <div class="divide-y divide-[var(--border)]">
          <Show when={notes().length === 0}>
            <div class="px-3 py-8 text-center text-sm text-[var(--text-muted)]">
              No notes yet
            </div>
          </Show>
          <For each={notes()}>
            {note => (
              <button
                class="w-full px-3 py-2.5 text-left transition-colors"
                classList={{
                  "bg-[var(--accent-subtle)]": selected()?.id === note.id,
                  "hover:bg-[var(--bg-subtle)]": selected()?.id !== note.id
                }}
                onClick={() => setSelectedId(note.id)}
              >
                <p class="truncate text-sm font-medium">{note.title || "Untitled"}</p>
                <p class="mt-0.5 text-xs text-[var(--text-muted)]">
                  {formatStamp(note.updatedAt)}
                </p>
              </button>
            )}
          </For>
        </div>
      </aside>

      {/* Editor area */}
      <div class="flex flex-1 flex-col gap-4">
        {/* Sync status bar */}
        <div class="flex items-center justify-between rounded-lg border border-[var(--border)] bg-[var(--surface)] px-4 py-2">
          <div class="flex items-center gap-2">
            <span
              class="h-2 w-2 rounded-full"
              classList={{
                "bg-[var(--success)]": syncBadge().label === "Synced",
                "bg-[var(--warning)]": syncBadge().label === "Saving..." || syncBadge().label === "Queued",
                "bg-[var(--error)]": syncBadge().label === "Sync issue",
                "bg-[var(--text-muted)]": syncBadge().label === "No local changes" || syncBadge().label === "Offline"
              }}
            />
            <span class="text-xs font-medium">{syncBadge().label}</span>
          </div>
          <span class="text-xs text-[var(--text-muted)]">{syncBadge().detail}</span>
        </div>

        {/* Editor */}
        <Show when={selected()}>
          <div class="grid flex-1 gap-4 lg:grid-cols-2">
            {/* Editor pane */}
            <div class="flex flex-col rounded-lg border border-[var(--border)] bg-[var(--surface)]">
              <div class="border-b border-[var(--border)] px-4 py-2">
                <input
                  class="w-full bg-transparent text-sm font-medium outline-none"
                  placeholder="Note title"
                  value={selected()?.title ?? ""}
                  onInput={event => {
                    const note = selected();
                    if (!note) return;
                    app.updateNote(note.id, event.currentTarget.value, note.content);
                  }}
                />
              </div>
              <textarea
                class="min-h-0 flex-1 resize-none bg-transparent p-4 text-sm outline-none"
                placeholder="Start writing..."
                value={selected()?.content ?? ""}
                onInput={event => {
                  const note = selected();
                  if (!note) return;
                  app.updateNote(note.id, note.title, event.currentTarget.value);
                }}
              />
            </div>

            {/* Preview pane */}
            <div class="flex flex-col rounded-lg border border-[var(--border)] bg-[var(--surface)]">
              <div class="border-b border-[var(--border)] px-4 py-2">
                <span class="text-xs font-medium uppercase tracking-wide text-[var(--text-muted)]">Preview</span>
              </div>
              <div class="flex-1 overflow-y-auto p-4">
                <MarkdownPreview content={selected()?.content ?? ""} />
              </div>
            </div>
          </div>
        </Show>

        <Show when={!selected()}>
          <div class="flex flex-1 items-center justify-center rounded-lg border border-[var(--border)] bg-[var(--surface)]">
            <div class="text-center">
              <p class="text-sm text-[var(--text-muted)]">Select a note or create a new one</p>
              <button
                class="button-primary mt-4 px-4 py-2 text-sm"
                onClick={() => void createNote()}
              >
                New note
              </button>
            </div>
          </div>
        </Show>
      </div>
    </div>
  );
}
