"use client";

import { useParams } from "next/navigation";
import { FileStack, Plus, Loader2 } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/trpc";
import { cn } from "@/lib/utils";
import { TemplateEditor } from "@/components/templates";

export default function TemplatesSettingsPage() {
  const params = useParams();
  const workspaceId =
    typeof params?.workspaceSlug === "string" ? params.workspaceSlug : "";
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const utils = api.useUtils();

  const { data, isLoading } = api.templates.list.useQuery(
    { workspaceId },
    { enabled: Boolean(workspaceId) },
  );
  const templates = data?.templates ?? [];

  const createMutation = api.templates.create.useMutation({
    onSuccess: (newTemplate) => {
      setSelectedId(newTemplate.id);
      void utils.templates.list.invalidate({ workspaceId });
    },
  });

  const getByIdQuery = api.templates.getById.useQuery(
    { id: selectedId! },
    { enabled: Boolean(workspaceId && selectedId) },
  );

  if (!workspaceId) {
    return (
      <div className="p-8 text-sm text-muted-foreground">
        No workspace selected.
      </div>
    );
  }

  const invalidateAfterSave = () => {
    void utils.templates.list.invalidate({ workspaceId });
    if (selectedId) void utils.templates.getById.invalidate({ id: selectedId });
  };

  return (
    <div className="flex h-full flex-col">
      <div className="flex shrink-0 items-center justify-between border-b px-6 py-4">
        <div className="flex items-center gap-3">
          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
            <FileStack className="size-5 text-primary" />
          </div>
          <h1 className="text-lg font-semibold">Templates</h1>
        </div>
        <Button
          size="sm"
          className="gap-1.5"
          onClick={() =>
            createMutation.mutate({
              workspaceId,
              name: "Untitled Template",
              targetType: "task",
              schema: { properties: [], defaultContent: "" },
            })
          }
          disabled={createMutation.isPending}
        >
          <Plus className="size-4" />
          New Template
        </Button>
      </div>

      <div className="flex min-h-0 flex-1">
        {/* Left: Template list */}
        <div className="w-64 shrink-0 overflow-y-auto border-r bg-muted/30 p-3">
          {isLoading ? (
            <div className="flex items-center justify-center py-10">
              <Loader2 className="size-5 animate-spin text-muted-foreground" />
            </div>
          ) : templates.length === 0 ? (
            <p className="py-4 text-center text-xs text-muted-foreground">
              No templates yet
            </p>
          ) : (
            <div className="flex flex-col gap-1">
              {templates.map((t) => (
                <button
                  key={t.id}
                  type="button"
                  onClick={() => setSelectedId(t.id)}
                  className={cn(
                    "rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-accent",
                    selectedId === t.id && "bg-accent font-medium",
                  )}
                >
                  <p className="truncate">{t.name}</p>
                  <p className="text-xs text-muted-foreground capitalize">
                    {t.targetType}
                  </p>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Right: Template editor */}
        <div className="flex-1 overflow-y-auto p-6">
          {selectedId ? (
            getByIdQuery.isLoading ? (
              <div className="flex h-full items-center justify-center">
                <Loader2 className="size-8 animate-spin text-muted-foreground" />
              </div>
            ) : getByIdQuery.data ? (
              <TemplateEditor
                key={selectedId}
                template={getByIdQuery.data}
                workspaceId={workspaceId}
                onSave={invalidateAfterSave}
              />
            ) : (
              <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
                Template not found
              </div>
            )
          ) : (
            <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
              Select a template or create a new one
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
