"use client";

import { useMemo } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { FileText, Plus } from "lucide-react";

import { api } from "@/lib/trpc";
import { Button } from "@/components/ui/button";

function formatUpdatedAt(value: Date | string): string {
  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);
  return date.toLocaleString();
}

export default function DocsPage() {
  const params = useParams();
  const router = useRouter();
  const utils = api.useUtils();

  const workspaceSlug =
    typeof params?.workspaceSlug === "string" ? params.workspaceSlug : undefined;

  const listQuery = api.objects.list.useQuery(
    { workspace: workspaceSlug!, parentId: undefined, limit: 200 },
    { enabled: Boolean(workspaceSlug) },
  );

  const createMutation = api.objects.create.useMutation({
    onSuccess: (created) => {
      if (workspaceSlug) {
        void utils.objects.list.invalidate({ workspace: workspaceSlug });
        router.push(`/${workspaceSlug}/docs/${created.id}`);
      }
    },
  });

  const documents = useMemo(() => {
    const rows = listQuery.data?.objects ?? [];
    return rows
      .filter((o) => o.type === "document")
      .slice()
      .sort((a, b) => {
        const ta = new Date(a.updatedAt).getTime();
        const tb = new Date(b.updatedAt).getTime();
        return tb - ta;
      });
  }, [listQuery.data?.objects]);

  return (
    <div className="mx-auto max-w-4xl px-8 py-10">
      <div className="mb-8 flex flex-wrap items-center justify-between gap-4">
        <h1 className="text-3xl font-bold tracking-tight">Documents</h1>
        <Button
          type="button"
          disabled={!workspaceSlug || createMutation.isPending}
          onClick={() => {
            if (!workspaceSlug) return;
            createMutation.mutate({
              type: "document",
              title: "Untitled",
              workspace: workspaceSlug,
              parentId: null,
            });
          }}
        >
          <Plus className="mr-2 size-4" />
          New Document
        </Button>
      </div>

      {listQuery.isLoading ? (
        <p className="text-sm text-muted-foreground">Loading documents…</p>
      ) : documents.length === 0 ? (
        <div className="rounded-lg border border-dashed border-border bg-muted/30 p-12 text-center text-sm text-muted-foreground">
          No documents yet. Create one to get started.
        </div>
      ) : (
        <ul className="divide-y divide-border rounded-lg border border-border bg-card shadow-sm">
          {documents.map((doc) => (
            <li key={doc.id}>
              <Link
                href={`/${workspaceSlug}/docs/${doc.id}`}
                className="flex items-center justify-between gap-4 px-4 py-4 transition-colors hover:bg-muted/40"
              >
                <span className="flex min-w-0 items-center gap-3">
                  <FileText className="size-5 shrink-0 text-muted-foreground" />
                  <span className="truncate font-medium">{doc.title}</span>
                </span>
                <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
                  {formatUpdatedAt(doc.updatedAt)}
                </span>
              </Link>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
