import { useState, useCallback } from 'react';
import { ChevronDown, Search, Zap, Play } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from './ui/dropdown-menu';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Badge } from './ui/badge';
import { ScrollArea } from './ui/scroll-area';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import { AvailableContext, ContextVariable, ContextVariableType } from '../types/workflow-context';

interface VariablePickerProps {
  /** Available context from preceding nodes */
  availableContext: AvailableContext;
  /** Callback when a variable is selected */
  onSelect: (variable: ContextVariable) => void;
  /** Whether the picker is disabled */
  disabled?: boolean;
  /** Optional type filter - only show variables of these types */
  allowedTypes?: ContextVariableType[];
}

/**
 * Dropdown button component for selecting and inserting workflow variables.
 *
 * Shows variables grouped by source node (Trigger and preceding Actions)
 * with search functionality and type badges.
 */
export function VariablePicker({
  availableContext,
  onSelect,
  disabled = false,
  allowedTypes,
}: VariablePickerProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [open, setOpen] = useState(false);

  // Filter groups and variables based on search query AND allowed types
  const filteredGroups = availableContext.groups
    .map((group) => ({
      ...group,
      variables: group.variables.filter((v) => {
        // First check type filter
        if (allowedTypes && allowedTypes.length > 0 && !allowedTypes.includes(v.type)) {
          return false;
        }
        // Then check search query
        return (
          v.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
          v.path.toLowerCase().includes(searchQuery.toLowerCase()) ||
          v.description.toLowerCase().includes(searchQuery.toLowerCase())
        );
      }),
    }))
    .filter((group) => group.variables.length > 0);

  // Calculate warning state for type filtering
  const totalAvailableVariables = availableContext.groups.reduce(
    (sum, g) => sum + g.variables.length,
    0,
  );
  const hasTypeFilter = allowedTypes && allowedTypes.length > 0;
  const noMatchingTypes =
    hasTypeFilter && totalAvailableVariables > 0 && filteredGroups.length === 0 && !searchQuery;

  const handleSelect = useCallback(
    (variable: ContextVariable) => {
      onSelect(variable);
      setOpen(false);
      setSearchQuery('');
    },
    [onSelect],
  );

  const getTypeColor = (type: string): string => {
    switch (type) {
      case 'string':
        return 'bg-blue-100 text-blue-800 border-blue-200';
      case 'integer':
        return 'bg-green-100 text-green-800 border-green-200';
      case 'boolean':
        return 'bg-purple-100 text-purple-800 border-purple-200';
      case 'datetime':
        return 'bg-orange-100 text-orange-800 border-orange-200';
      case 'array':
        return 'bg-gray-100 text-gray-800 border-gray-200';
      default:
        return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  const isEmpty = availableContext.groups.length === 0;

  return (
    <DropdownMenu open={open} onOpenChange={setOpen}>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          disabled={disabled || isEmpty}
          className="h-8 px-2 text-xs border-slate-400 hover:border-cyan-600 shrink-0"
          title={
            isEmpty
              ? 'No variables available (add preceding nodes)'
              : noMatchingTypes
                ? `No ${allowedTypes?.join(' or ')} variables available`
                : 'Insert variable from workflow context'
          }
        >
          <Zap className="w-3 h-3 mr-1" />
          Insert Variable
          <ChevronDown className="w-3 h-3 ml-1" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align="end"
        className="w-80"
        onCloseAutoFocus={(e) => e.preventDefault()}
      >
        {/* Search input */}
        <div className="p-2">
          <div className="relative">
            <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <Input
              placeholder="Search variables..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-8 h-8 text-sm"
            />
          </div>
        </div>
        <DropdownMenuSeparator />

        {/* Variable groups */}
        <ScrollArea className="max-h-72">
          {filteredGroups.length === 0 ? (
            <div className="p-4 text-center text-sm">
              {searchQuery ? (
                <span className="text-slate-500">No matching variables found</span>
              ) : noMatchingTypes ? (
                <div className="text-amber-600">
                  <span className="block font-medium mb-1">No compatible variables</span>
                  <span className="text-xs">
                    This field requires {allowedTypes?.join(' or ')} type variables
                  </span>
                </div>
              ) : (
                <span className="text-slate-500">No variables available</span>
              )}
            </div>
          ) : (
            filteredGroups.map((group, groupIndex) => (
              <DropdownMenuGroup key={group.namespace}>
                {groupIndex > 0 && <DropdownMenuSeparator />}
                <DropdownMenuLabel className="flex items-center gap-2">
                  {group.sourceType === 'trigger' ? (
                    <Play className="w-3 h-3 text-success" />
                  ) : (
                    <Zap className="w-3 h-3 text-cyan-600" />
                  )}
                  <span className="truncate">{group.sourceName}</span>
                </DropdownMenuLabel>
                {group.variables.map((variable) => (
                  <TooltipProvider key={variable.path}>
                    <Tooltip delayDuration={300}>
                      <TooltipTrigger asChild>
                        <DropdownMenuItem
                          onSelect={() => handleSelect(variable)}
                          className="flex items-center justify-between cursor-pointer py-2"
                        >
                          <div className="flex flex-col gap-0.5 min-w-0">
                            <span className="text-sm font-medium truncate">{variable.label}</span>
                            <code className="text-xs text-slate-500 font-mono truncate">
                              {`{{${variable.path}}}`}
                            </code>
                          </div>
                          <Badge
                            variant="outline"
                            className={`text-xs ml-2 shrink-0 ${getTypeColor(variable.type)}`}
                          >
                            {variable.type}
                          </Badge>
                        </DropdownMenuItem>
                      </TooltipTrigger>
                      <TooltipContent side="left" className="max-w-xs">
                        <p className="text-sm">{variable.description}</p>
                        <p className="text-xs text-slate-500 mt-1">
                          Example: <code>{variable.example}</code>
                        </p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                ))}
              </DropdownMenuGroup>
            ))
          )}
        </ScrollArea>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
