import React from 'react';
import { useCustomVariables } from '@/hooks/useCustomVariables';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';

export function CustomVariablesInserter({ clientId, onSelect, onClose }) {
  const { variables = [] } = useCustomVariables(clientId);

  if (!variables.length) {
    return (
      <div className="p-4 text-sm text-muted-foreground">
        No custom variables available for this association.
      </div>
    );
  }

  // Group by category
  const grouped = variables.reduce((acc, v) => {
    const cat = v.category || 'general';
    if (!acc[cat]) acc[cat] = [];
    acc[cat].push(v);
    return acc;
  }, {});

  return (
    <ScrollArea className="max-h-60">
      <div className="p-2 space-y-2">
        {Object.entries(grouped).map(([category, vars]) => (
          <div key={category}>
            <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground px-2 py-1">
              {category}
            </div>
            {vars.map((v) => (
              <Button
                key={v.id}
                variant="ghost"
                size="sm"
                className="w-full justify-start text-sm font-mono"
                onClick={() => {
                  onSelect?.(v.variable_name);
                  onClose?.();
                }}
              >
                <span className="text-primary">{`{{${v.variable_name}}}`}</span>
                <span className="ml-2 text-muted-foreground font-sans text-xs truncate">{v.display_label}</span>
              </Button>
            ))}
          </div>
        ))}
      </div>
    </ScrollArea>
  );
}
