import {
  ChevronRight,
  Clock3,
  Database,
  FileText,
  Folder,
  FolderGit2,
  FolderOpen,
  LogIn,
  LogOut,
  PanelLeftClose,
  PanelLeftOpen,
  RefreshCw,
  Shield,
  UserPlus,
  Users,
} from "lucide-preact";
import { useEffect, useState } from "preact/hooks";

type Role = "admin" | "editor" | "viewer";
type View = "workspace" | "users";

type User = {
  id: string;
  email: string;
  displayName: string;
  role: Role;
  createdAt: string;
  lastSeenAt?: string;
};

type DocumentRecord = {
  path: string;
  title: string;
  currentHash: string;
  updatedAt: string;
};

type Workspace = {
  sourceDir: string;
  storeDir: string;
  databasePath: string;
  documentCount: number;
  userCount: number;
  webDistDir: string;
};

type WorkspaceResponse = {
  workspace: Workspace;
  documents: DocumentRecord[];
};

type Session = {
  user: User;
};

type BrowserItem = {
  type: "folder" | "document";
  name: string;
  path: string;
  document?: DocumentRecord;
  indexDocument?: DocumentRecord;
};

type BrowserColumn = {
  title: string;
  prefix: string;
  items: BrowserItem[];
};

const sessionKey = "mdhub.admin.session";

export function App() {
  const [session, setSession] = useState<Session | null>(() => readSession());
  const [activeView, setActiveView] = useState<View>("workspace");
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [users, setUsers] = useState<User[]>([]);
  const [workspace, setWorkspace] = useState<WorkspaceResponse | null>(null);
  const [syncing, setSyncing] = useState(false);
  const [lastSyncedAt, setLastSyncedAt] = useState("");
  const [activePath, setActivePath] = useState("");
  const [selectedUserId, setSelectedUserId] = useState("");

  async function refresh() {
    if (!session) {
      return;
    }
    const [usersResponse, workspaceResponse] = await Promise.all([
      api<{ users: User[] }>("/api/admin/users"),
      api<WorkspaceResponse>("/api/admin/workspace"),
    ]);
    setUsers(usersResponse.users);
    setWorkspace(workspaceResponse);
    setLastSyncedAt(new Date().toISOString());
  }

  useEffect(() => {
    void refresh();
  }, [session?.user.email]);

  useEffect(() => {
    const documents = workspace?.documents ?? [];
    if (
      documents.length > 0 &&
      !isKnownDocumentLocation(documents, activePath)
    ) {
      setActivePath(documents[0].path);
    }
  }, [workspace?.documents, activePath]);

  useEffect(() => {
    if (users.length > 0 && !users.some((user) => user.id === selectedUserId)) {
      setSelectedUserId(users[0].id);
    }
  }, [users, selectedUserId]);

  async function handleLogin(email: string, displayName: string) {
    const response = await api<{ user: User }>("/api/admin/login", {
      method: "POST",
      body: JSON.stringify({ email, displayName, role: "admin" }),
    });
    const next = { user: response.user };
    localStorage.setItem(sessionKey, JSON.stringify(next));
    setSession(next);
  }

  async function handleCreateUser(input: {
    email: string;
    displayName: string;
    role: Role;
  }) {
    const response = await api<{ user: User }>("/api/admin/users", {
      method: "POST",
      body: JSON.stringify(input),
    });
    await refresh();
    setSelectedUserId(response.user.id);
  }

  async function handleSync() {
    setSyncing(true);
    try {
      await api("/api/admin/workspace/sync", { method: "POST" });
      await refresh();
    } finally {
      setSyncing(false);
    }
  }

  function logout() {
    localStorage.removeItem(sessionKey);
    setSession(null);
    setUsers([]);
    setWorkspace(null);
    setActivePath("");
    setSelectedUserId("");
  }

  if (!session) {
    return <LoginScreen onLogin={handleLogin} />;
  }

  const selectedDocument = selectDocument(
    workspace?.documents ?? [],
    activePath,
  );
  const selectedUser =
    users.find((user) => user.id === selectedUserId) ?? users[0];

  return (
    <main class={`admin-shell ${sidebarOpen ? "" : "is-collapsed"}`}>
      <aside class="admin-sidebar">
        <div class="sidebar-header">
          <a class="brand" href="/docs" title="Open public docs">
            <Shield size={18} />
            <span>MD Hub</span>
          </a>
          <button
            class="icon-button"
            type="button"
            onClick={() => setSidebarOpen((open) => !open)}
            aria-label={sidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
          >
            {sidebarOpen ? (
              <PanelLeftClose size={17} />
            ) : (
              <PanelLeftOpen size={17} />
            )}
          </button>
        </div>

        <nav class="nav-list" aria-label="Admin sections">
          <button
            class={activeView === "workspace" ? "is-active" : ""}
            type="button"
            onClick={() => setActiveView("workspace")}
            title="Workspace"
          >
            <FolderGit2 size={17} />
            <span>Workspace</span>
          </button>
          <button
            class={activeView === "users" ? "is-active" : ""}
            type="button"
            onClick={() => setActiveView("users")}
            title="Users"
          >
            <Users size={17} />
            <span>Users</span>
          </button>
        </nav>

        <button
          class="nav-button"
          type="button"
          onClick={logout}
          title="Sign out"
        >
          <LogOut size={16} />
          <span>Sign out</span>
        </button>
      </aside>

      <section class="admin-main">
        <header class="compact-topbar">
          <div>
            <span class="section-label">{activeView}</span>
            <strong>
              {activeView === "workspace" ? "Documents" : "Accounts"}
            </strong>
          </div>
          <div class="topbar-actions">
            {activeView === "workspace" && (
              <button
                type="button"
                class="primary-button sync-button"
                onClick={handleSync}
                disabled={syncing}
                aria-label="Sync workspace"
              >
                <RefreshCw size={15} />
                <span>Sync</span>
              </button>
            )}
            <span class="sync-label">
              <Clock3 size={14} />
              {syncing
                ? "Syncing"
                : lastSyncedAt
                  ? `Synced ${formatTime(lastSyncedAt)}`
                  : "Not synced"}
            </span>
          </div>
        </header>

        {activeView === "workspace" ? (
          <WorkspaceView
            data={workspace}
            activePath={activePath}
            selectedDocument={selectedDocument}
            onSelectPath={setActivePath}
          />
        ) : (
          <UsersView
            users={users}
            selectedUser={selectedUser}
            onSelectUser={setSelectedUserId}
            onCreateUser={handleCreateUser}
          />
        )}
      </section>
    </main>
  );
}

function LoginScreen(props: {
  onLogin: (email: string, displayName: string) => Promise<void>;
}) {
  const [email, setEmail] = useState("admin@example.com");
  const [displayName, setDisplayName] = useState("Admin");
  const [error, setError] = useState("");

  async function submit(event: Event) {
    event.preventDefault();
    setError("");
    try {
      await props.onLogin(email, displayName);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Login failed");
    }
  }

  return (
    <main class="login-shell">
      <form class="login-panel" onSubmit={submit}>
        <div class="login-mark">
          <Shield size={20} />
        </div>
        <h1>Admin login</h1>
        <label>
          Email
          <input
            type="email"
            value={email}
            onInput={(event) => setEmail(event.currentTarget.value)}
            required
          />
        </label>
        <label>
          Display name
          <input
            type="text"
            value={displayName}
            onInput={(event) => setDisplayName(event.currentTarget.value)}
            required
          />
        </label>
        {error && <p class="form-error">{error}</p>}
        <button type="submit" class="primary-button">
          <LogIn size={15} />
          Sign in
        </button>
      </form>
    </main>
  );
}

function WorkspaceView(props: {
  data: WorkspaceResponse | null;
  activePath: string;
  selectedDocument?: DocumentRecord;
  onSelectPath: (path: string) => void;
}) {
  const documents = props.data?.documents ?? [];
  const columns = buildDocumentColumns(documents, props.activePath);

  return (
    <div class="workspace-grid">
      <section class="column-browser" aria-label="Workspace files">
        {columns.map((column) => (
          <div class="browser-column" key={column.prefix || "root"}>
            <header>
              <Folder size={15} />
              {column.title}
            </header>
            <div class="item-list">
              {column.items.map((item) => (
                <button
                  class={
                    isActiveItem(item, props.activePath)
                      ? "list-item is-active"
                      : "list-item"
                  }
                  type="button"
                  key={`${item.type}:${item.path}`}
                  onClick={() =>
                    props.onSelectPath(item.indexDocument?.path ?? item.path)
                  }
                >
                  {item.type === "folder" ? (
                    isActiveItem(item, props.activePath) ? (
                      <FolderOpen size={15} />
                    ) : (
                      <Folder size={15} />
                    )
                  ) : (
                    <FileText size={15} />
                  )}
                  <span>{item.name}</span>
                  {item.type === "folder" && <ChevronRight size={14} />}
                </button>
              ))}
              {column.items.length === 0 && (
                <p class="empty-state">No documents</p>
              )}
            </div>
          </div>
        ))}
      </section>

      <WorkspaceDetails
        workspace={props.data?.workspace}
        document={props.selectedDocument}
      />
    </div>
  );
}

function WorkspaceDetails(props: {
  workspace?: Workspace;
  document?: DocumentRecord;
}) {
  return (
    <aside class="detail-panel">
      <header class="detail-header">
        <Database size={17} />
        <span>Details</span>
      </header>

      {props.document ? (
        <>
          <h2>{props.document.title}</h2>
          <a class="open-link" href={documentHref(props.document.path)}>
            Open document
          </a>
          <dl class="detail-list">
            <div>
              <dt>File</dt>
              <dd>{props.document.path}</dd>
            </div>
            <div>
              <dt>Hash</dt>
              <dd>
                <code>{props.document.currentHash.slice(0, 12)}</code>
              </dd>
            </div>
            <div>
              <dt>Updated</dt>
              <dd>{formatDate(props.document.updatedAt)}</dd>
            </div>
          </dl>
        </>
      ) : (
        <p class="empty-state">Select a document.</p>
      )}

      {props.workspace && (
        <dl class="detail-list compact">
          <div>
            <dt>Documents</dt>
            <dd>{props.workspace.documentCount}</dd>
          </div>
          <div>
            <dt>Content</dt>
            <dd>{props.workspace.sourceDir}</dd>
          </div>
          <div>
            <dt>Storage</dt>
            <dd>{props.workspace.storeDir}</dd>
          </div>
          <div>
            <dt>Database</dt>
            <dd>{props.workspace.databasePath}</dd>
          </div>
        </dl>
      )}
    </aside>
  );
}

function UsersView(props: {
  users: User[];
  selectedUser?: User;
  onSelectUser: (id: string) => void;
  onCreateUser: (input: {
    email: string;
    displayName: string;
    role: Role;
  }) => Promise<void>;
}) {
  return (
    <div class="workspace-grid">
      <section class="browser-column user-column" aria-label="Users">
        <header>Users</header>
        <div class="item-list">
          {props.users.map((user) => (
            <button
              class={
                user.id === props.selectedUser?.id
                  ? "list-item is-active"
                  : "list-item"
              }
              type="button"
              key={user.id}
              onClick={() => props.onSelectUser(user.id)}
            >
              <Users size={15} />
              <span>{user.displayName}</span>
              <small>{user.role}</small>
            </button>
          ))}
        </div>
      </section>

      <UserDetails
        selectedUser={props.selectedUser}
        onCreateUser={props.onCreateUser}
      />
    </div>
  );
}

function UserDetails(props: {
  selectedUser?: User;
  onCreateUser: (input: {
    email: string;
    displayName: string;
    role: Role;
  }) => Promise<void>;
}) {
  const [email, setEmail] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [role, setRole] = useState<Role>("viewer");

  async function submit(event: Event) {
    event.preventDefault();
    await props.onCreateUser({ email, displayName, role });
    setEmail("");
    setDisplayName("");
    setRole("viewer");
  }

  return (
    <aside class="detail-panel">
      <header class="detail-header">
        <UserPlus size={17} />
        <span>Add user</span>
      </header>

      <form class="stack-form" onSubmit={submit}>
        <input
          type="email"
          placeholder="email@example.com"
          value={email}
          onInput={(event) => setEmail(event.currentTarget.value)}
          required
        />
        <input
          type="text"
          placeholder="Display name"
          value={displayName}
          onInput={(event) => setDisplayName(event.currentTarget.value)}
          required
        />
        <select
          value={role}
          onChange={(event) => setRole(event.currentTarget.value as Role)}
        >
          <option value="viewer">Viewer</option>
          <option value="editor">Editor</option>
          <option value="admin">Admin</option>
        </select>
        <button type="submit" class="primary-button">
          <UserPlus size={15} />
          Add
        </button>
      </form>

      {props.selectedUser && (
        <>
          <h2>{props.selectedUser.displayName}</h2>
          <dl class="detail-list">
            <div>
              <dt>Email</dt>
              <dd>{props.selectedUser.email}</dd>
            </div>
            <div>
              <dt>Role</dt>
              <dd>{props.selectedUser.role}</dd>
            </div>
            <div>
              <dt>Created</dt>
              <dd>{formatDate(props.selectedUser.createdAt)}</dd>
            </div>
          </dl>
        </>
      )}
    </aside>
  );
}

function buildDocumentColumns(
  documents: DocumentRecord[],
  activePath: string,
): BrowserColumn[] {
  const activeSegments = activePath.split("/").filter(Boolean);
  const prefixes = [""];
  const maxFolderDepth = activePath.endsWith(".md")
    ? activeSegments.length - 1
    : activeSegments.length;

  for (let index = 0; index < maxFolderDepth; index += 1) {
    prefixes.push(activeSegments.slice(0, index + 1).join("/"));
  }

  return prefixes.map((prefix) => ({
    title: prefix ? folderLabel(prefix) : "Documents",
    prefix,
    items: collectItems(documents, prefix),
  }));
}

function collectItems(
  documents: DocumentRecord[],
  prefix: string,
): BrowserItem[] {
  const items = new Map<string, BrowserItem>();
  const prefixWithSlash = prefix ? `${prefix}/` : "";

  for (const document of documents) {
    if (!document.path.startsWith(prefixWithSlash)) {
      continue;
    }

    const remainder = document.path.slice(prefixWithSlash.length);
    if (!remainder || remainder === "index.md") {
      continue;
    }

    const [nextSegment, ...rest] = remainder.split("/");
    if (rest.length > 0) {
      const folderPath = `${prefixWithSlash}${nextSegment}`;
      const indexDocument = documents.find(
        (candidate) => candidate.path === `${folderPath}/index.md`,
      );
      items.set(folderPath, {
        type: "folder",
        name: folderLabel(nextSegment),
        path: folderPath,
        indexDocument,
      });
      continue;
    }

    items.set(document.path, {
      type: "document",
      name: document.title || fileLabel(document.path),
      path: document.path,
      document,
    });
  }

  return [...items.values()].sort((left, right) => {
    if (left.type !== right.type) {
      return left.type === "folder" ? -1 : 1;
    }
    return left.name.localeCompare(right.name);
  });
}

function selectDocument(documents: DocumentRecord[], activePath: string) {
  if (!activePath) {
    return documents[0];
  }
  return (
    documents.find((document) => document.path === activePath) ??
    documents.find((document) => document.path === `${activePath}/index.md`)
  );
}

function isKnownDocumentLocation(documents: DocumentRecord[], path: string) {
  if (!path) {
    return false;
  }
  return documents.some(
    (document) =>
      document.path === path ||
      document.path === `${path}/index.md` ||
      document.path.startsWith(`${path}/`),
  );
}

function isActiveItem(item: BrowserItem, activePath: string) {
  return (
    activePath === item.path ||
    activePath === item.indexDocument?.path ||
    activePath.startsWith(`${item.path}/`)
  );
}

function documentHref(path: string) {
  return `/docs/${path.replace(/(^|\/)index\.md$/, "").replace(/\.md$/, "")}`;
}

function folderLabel(path: string) {
  return fileLabel(path.split("/").filter(Boolean).at(-1) ?? path);
}

function fileLabel(path: string) {
  return path
    .replace(/\.md$/, "")
    .replace(/[-_]/g, " ")
    .replace(/\b\w/g, (match) => match.toUpperCase());
}

async function api<T = unknown>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(path, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      ...(init?.headers ?? {}),
    },
  });
  if (!response.ok) {
    const text = await response.text();
    throw new Error(text || response.statusText);
  }
  return response.json() as Promise<T>;
}

function readSession(): Session | null {
  try {
    const raw = localStorage.getItem(sessionKey);
    return raw ? (JSON.parse(raw) as Session) : null;
  } catch {
    return null;
  }
}

function formatDate(value: string) {
  if (!value) {
    return "";
  }
  return new Intl.DateTimeFormat(undefined, {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(new Date(value));
}

function formatTime(value: string) {
  return new Intl.DateTimeFormat(undefined, {
    hour: "numeric",
    minute: "2-digit",
  }).format(new Date(value));
}
