"use client";

import { ChevronDown } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { api } from "@/lib/trpc";
import { cn } from "@/lib/utils";

const BUILTIN = [
  { value: "title", label: "Task title" },
  { value: "description", label: "Description" },
  { value: "status", label: "Status" },
] as const;

export function FormMappingPicker({
  workspaceHandle,
  value,
  onChange,
  disabled,
  className,
}: {
  workspaceHandle: string;
  value: string | null;
  onChange: (next: string | null) => void;
  disabled?: boolean;
  className?: string;
}) {
  const { data, isLoading } = api.properties.listDefinitions.useQuery(
    { workspace: workspaceHandle },
    { enabled: Boolean(workspaceHandle) },
  );

  const definitions = data?.definitions ?? [];

  const labelFor = (v: string | null) => {
    if (v === null || v === "") return "No mapping";
    const builtin = BUILTIN.find((b) => b.value === v);
    if (builtin) return builtin.label;
    const def = definitions.find((d) => d.id === v);
    return def?.name ?? v;
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          type="button"
          variant="outline"
          disabled={disabled || isLoading}
          className={cn("w-full justify-between font-normal", className)}
        >
          <span className="truncate">{labelFor(value)}</span>
          <ChevronDown className="size-4 shrink-0 opacity-50" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="max-h-64 w-[var(--radix-dropdown-menu-trigger-width)] overflow-y-auto">
        <DropdownMenuLabel>Task fields</DropdownMenuLabel>
        <DropdownMenuItem onClick={() => onChange(null)}>
          No mapping
        </DropdownMenuItem>
        {BUILTIN.map((b) => (
          <DropdownMenuItem key={b.value} onClick={() => onChange(b.value)}>
            {b.label}
          </DropdownMenuItem>
        ))}
        <DropdownMenuSeparator />
        <DropdownMenuLabel>Custom properties</DropdownMenuLabel>
        {definitions.length === 0 ? (
          <DropdownMenuItem disabled>No custom properties</DropdownMenuItem>
        ) : (
          definitions.map((d) => (
            <DropdownMenuItem key={d.id} onClick={() => onChange(d.id)}>
              {d.name}
            </DropdownMenuItem>
          ))
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
