import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
  CommandMenuRow,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@learnitive/ui-components';
import { Link } from 'lucide-react';
import React from 'react';

export type VisualReferenceTarget = {
  target: string;
  file: string;
  line: number;
  name?: string;
};

export function LatexVisualReferencePicker({
  open,
  targets,
  onOpenChange,
  onSelect,
  title = 'Insert reference',
  description = 'Choose a label already defined in this project.',
  currentTarget,
  onNavigateCurrent,
}: {
  open: boolean;
  targets: readonly VisualReferenceTarget[];
  onOpenChange: (open: boolean) => void;
  onSelect: (target: string) => void;
  title?: string;
  description?: string;
  currentTarget?: string;
  onNavigateCurrent?: () => void;
}) {
  const unique = React.useMemo(() => {
    const seen = new Set<string>();
    return targets.filter((item) => {
      if (!item.target || seen.has(item.target)) return false;
      seen.add(item.target);
      return true;
    });
  }, [targets]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </DialogHeader>
        {currentTarget && onNavigateCurrent && (
          <button
            type="button"
            className="cursor-pointer rounded-md border px-3 py-2 text-left text-sm hover:bg-muted"
            onClick={onNavigateCurrent}
          >
            Go to current target · <span className="font-mono">{currentTarget}</span>
          </button>
        )}
        <Command className="rounded-md border">
          <CommandInput autoFocus placeholder="Search labels..." />
          <CommandEmpty>No project labels found.</CommandEmpty>
          <CommandList className="max-h-72">
            {unique.map((item) => (
              <CommandItem
                key={`${item.file}:${item.target}:${item.line}`}
                value={`${item.target} ${item.name ?? ''} ${item.file}`}
                onSelect={() => onSelect(item.target)}
              >
                <CommandMenuRow
                  icon={<Link aria-hidden />}
                  title={item.target}
                  description={`${item.file}:${item.line}${item.name ? ` · ${item.name}` : ''}`}
                />
              </CommandItem>
            ))}
          </CommandList>
        </Command>
      </DialogContent>
    </Dialog>
  );
}
