"use client";

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

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

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 FormsListPage() {
  const params = useParams();
  const router = useRouter();
  const utils = api.useUtils();

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

  const listQuery = api.forms.list.useQuery(
    { workspaceId: workspaceId! },
    { enabled: Boolean(workspaceId) },
  );

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

  const forms = useMemo(
    () => listQuery.data?.forms ?? [],
    [listQuery.data?.forms],
  );

  return (
    <div className="mx-auto max-w-5xl px-6 py-10 sm:px-10">
      <div className="mb-8 flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Forms</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Build forms that create or update tasks in this workspace.
          </p>
        </div>
        <Button
          type="button"
          disabled={!workspaceId || createMutation.isPending}
          onClick={() => {
            if (!workspaceId) return;
            createMutation.mutate({
              workspaceId,
              title: "Untitled form",
            });
          }}
        >
          <Plus className="mr-2 size-4" />
          New form
        </Button>
      </div>

      {listQuery.isLoading ? (
        <p className="text-sm text-muted-foreground">Loading forms…</p>
      ) : forms.length === 0 ? (
        <div className="rounded-lg border border-dashed border-border bg-muted/30 p-12 text-center text-sm text-muted-foreground">
          No forms yet. Create one to open the form builder.
        </div>
      ) : (
        <ul className="grid gap-4 sm:grid-cols-2">
          {forms.map((form) => (
            <li key={form.id}>
              <Link
                href={`/${workspaceId}/forms/${form.id}/edit`}
                className="flex h-full flex-col rounded-xl border border-border bg-card p-5 shadow-sm transition-colors hover:border-primary/30 hover:bg-muted/20"
              >
                <div className="flex items-start gap-3">
                  <span className="mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
                    <ClipboardList className="size-5" />
                  </span>
                  <div className="min-w-0 flex-1">
                    <p className="truncate font-semibold text-foreground">
                      {form.title}
                    </p>
                    {form.description ? (
                      <p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
                        {form.description}
                      </p>
                    ) : null}
                    <div className="mt-3 flex flex-wrap items-center gap-2">
                      <Badge
                        variant={form.isPublished ? "default" : "secondary"}
                      >
                        {form.isPublished ? "Published" : "Draft"}
                      </Badge>
                      <span className="text-xs text-muted-foreground tabular-nums">
                        Updated {formatUpdatedAt(form.updatedAt)}
                      </span>
                    </div>
                  </div>
                </div>
              </Link>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
