"use client";

import * as React from "react";
import { Loader2 } from "lucide-react";

import { FormRenderer } from "@/components/forms/form-renderer";
import { Button } from "@/components/ui/button";
import type { ViewConfig } from "@/lib/hooks/use-view-data";
import { useWorkspaceStore } from "@/lib/stores/workspace-store";
import { api } from "@/lib/trpc";
import { cn } from "@/lib/utils";

export interface FormViewProps {
  config: ViewConfig;
  className?: string;
}

export function FormView({ config, className }: FormViewProps) {
  void config;

  const workspace = useWorkspaceStore((s) => s.currentWorkspace);
  const workspaceHandle = workspace?.slug ?? workspace?.id;

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

  const [selectedId, setSelectedId] = React.useState<string | null>(null);

  const forms = listQuery.data?.forms ?? [];

  if (!workspaceHandle) {
    return (
      <div className={cn("p-6 text-sm text-muted-foreground", className)}>
        Select a workspace to use forms.
      </div>
    );
  }

  if (listQuery.isPending) {
    return (
      <div className={cn("flex flex-1 items-center justify-center py-16", className)}>
        <Loader2 className="size-8 animate-spin text-muted-foreground" aria-hidden />
        <span className="sr-only">Loading forms</span>
      </div>
    );
  }

  if (listQuery.isError) {
    return (
      <div className={cn("p-6 text-sm text-muted-foreground", className)}>
        Could not load forms for this workspace.
      </div>
    );
  }

  if (forms.length === 0) {
    return (
      <div className={cn("p-6 text-sm text-muted-foreground", className)}>
        No forms in this workspace yet. Create a form to show it here.
      </div>
    );
  }

  return (
    <div className={cn("flex min-h-0 flex-1 flex-col gap-4 p-4", className)}>
      <div className="flex flex-wrap items-center gap-2">
        <label htmlFor="form-view-picker" className="text-sm font-medium text-muted-foreground">
          Form
        </label>
        <select
          id="form-view-picker"
          value={selectedId ?? ""}
          onChange={(e) => setSelectedId(e.target.value || null)}
          className={cn(
            "h-9 min-w-[200px] rounded-md border border-input bg-background px-3 text-sm",
            "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
          )}
        >
          <option value="">Choose a form…</option>
          {forms.map((f) => (
            <option key={f.id} value={f.id}>
              {f.title}
            </option>
          ))}
        </select>
        {selectedId ? (
          <Button type="button" variant="ghost" size="sm" onClick={() => setSelectedId(null)}>
            Clear
          </Button>
        ) : null}
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto rounded-lg border border-border bg-card p-6">
        {selectedId ? (
          <FormRenderer key={selectedId} formId={selectedId} workspaceHandle={workspaceHandle} />
        ) : (
          <p className="text-sm text-muted-foreground">
            Pick a form above to fill it out in this view.
          </p>
        )}
      </div>
    </div>
  );
}
