import { useState, useEffect } from 'react';
import { Label } from './ui/label';
import { Button } from './ui/button';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from './ui/command';
import { VariableInput } from './VariableInput';
import { ActionField } from '../types/action';
import { AvailableContext } from '../types/workflow-context';
import { Loader2, Zap, ChevronsUpDown, Check } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import { cn } from '@/lib/utils';

interface SelectOption {
  value: string;
  label: string;
  breadcrumb?: string;
  description?: string;
  icon?: string;
  disabled?: boolean;
  group?: string;
}

interface CombinedSelectorFieldProps {
  /** The selector field schema (has selector_for property) */
  selectorField: ActionField;
  /** The target ID field schema */
  targetField: ActionField;
  /** Field name of the selector */
  selectorFieldName: string;
  /** Field name of the target ID */
  targetFieldName: string;
  /** Current value of the target ID field */
  targetValue: string;
  /** Available options for the dropdown */
  options: SelectOption[];
  /** Loading state for options */
  isLoading: boolean;
  /** Error message for options loading */
  error?: string;
  /** Whether dependency is met */
  dependencyMet: boolean;
  /** Dependency field label for message */
  dependencyLabel?: string;
  /** Handler for value changes - called with target field name and value */
  onChange: (fieldName: string, value: string) => void;
  /** Available context for variable picker */
  availableContext: AvailableContext;
  /** Validation error for the field */
  validationError?: string;
}

type InputMode = 'search' | 'map';

/**
 * Combined selector field that merges a search dropdown with variable mapping.
 *
 * Provides two modes:
 * - Search: Searchable combobox to select from options - shows names, hides UUIDs
 * - Map: Enter dynamic variable like {{Create_Page.id}} or paste raw UUID
 */
export function CombinedSelectorField({
  selectorField,
  targetField,
  selectorFieldName: _selectorFieldName,
  targetFieldName,
  targetValue,
  options,
  isLoading,
  error,
  dependencyMet,
  dependencyLabel,
  onChange,
  availableContext,
  validationError,
}: CombinedSelectorFieldProps) {
  // Combobox open state
  const [open, setOpen] = useState(false);

  // Default to search mode if dependency is met
  const [mode, setMode] = useState<InputMode>(dependencyMet ? 'search' : 'map');

  // Auto-switch to map if dependency not met
  useEffect(() => {
    if (!dependencyMet && mode === 'search') {
      setMode('map');
    }
  }, [dependencyMet, mode]);

  // Auto-switch to search when options become available and value matches an option
  useEffect(() => {
    if (dependencyMet && options.length > 0) {
      const valueMatchesOption = options.some((opt) => opt.value === targetValue);
      if (valueMatchesOption && mode === 'map') {
        setMode('search');
      }
    }
  }, [dependencyMet, options, targetValue, mode]);

  const handleModeChange = (newMode: InputMode) => {
    setMode(newMode);
  };

  const handleSelectChange = (value: string) => {
    onChange(targetFieldName, value);
    setOpen(false);
  };

  const handleMapChange = (value: string) => {
    onChange(targetFieldName, value);
  };

  // Use target field's label and required status for display
  const label = targetField.label || selectorField.label;
  const isRequired = targetField.required;

  // Get description based on mode
  const getDescription = () => {
    if (mode === 'search') {
      return 'Search and select from available options';
    }
    return 'Enter a variable like {{Create_Page.id}} or paste a UUID';
  };

  const placeholder = '{{trigger.page_id}} or paste UUID';

  // Find selected option for display
  const selectedOption = options.find((opt) => opt.value === targetValue);

  return (
    <div className="space-y-2">
      {/* Label */}
      <Label className="text-slate-900">
        {label}
        {isRequired && <span className="text-red-600 ml-1">*</span>}
      </Label>

      {/* Mode Toggle */}
      <div className="flex rounded-md border border-slate-400 overflow-hidden w-fit">
        <button
          type="button"
          onClick={() => handleModeChange('search')}
          disabled={!dependencyMet}
          className={`px-3 py-1.5 text-sm transition-colors ${
            mode === 'search'
              ? 'bg-cyan-600 text-white'
              : dependencyMet
                ? 'bg-white text-slate-900 hover:bg-slate-100'
                : 'bg-gray-100 text-gray-400 cursor-not-allowed'
          }`}
        >
          Search
        </button>
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                type="button"
                onClick={() => handleModeChange('map')}
                className={`px-2.5 py-1.5 border-l border-slate-400 transition-colors ${
                  mode === 'map'
                    ? 'bg-cyan-600 text-white'
                    : 'bg-white text-slate-900 hover:bg-slate-100'
                }`}
              >
                <Zap className="w-4 h-4" />
              </button>
            </TooltipTrigger>
            <TooltipContent side="top">Map dynamic variable or paste ID</TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </div>

      {/* Search Mode - Searchable Combobox */}
      {mode === 'search' && (
        <>
          {!dependencyMet ? (
            <div className="text-sm text-slate-500 italic">
              Select {dependencyLabel || 'the required field'} first
            </div>
          ) : isLoading ? (
            <div className="flex items-center gap-2 text-sm text-slate-500">
              <Loader2 className="w-4 h-4 animate-spin" />
              Loading options...
            </div>
          ) : error ? (
            <div className="text-sm text-red-600">{error}</div>
          ) : (
            <Popover open={open} onOpenChange={setOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={open}
                  className="w-full justify-between border-slate-400 bg-white hover:bg-slate-100 text-left font-normal h-auto min-h-[38px] py-2"
                >
                  <span className="truncate">
                    {selectedOption
                      ? selectedOption.breadcrumb || selectedOption.label
                      : 'Select an option...'}
                  </span>
                  <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
                <Command>
                  <CommandInput placeholder="Search..." />
                  <CommandList>
                    <CommandEmpty>No results found.</CommandEmpty>
                    <CommandGroup>
                      {options.map((option) => (
                        <CommandItem
                          key={option.value}
                          value={option.breadcrumb || option.label}
                          onSelect={() => handleSelectChange(option.value)}
                          className="cursor-pointer"
                        >
                          <Check
                            className={cn(
                              'mr-2 h-4 w-4',
                              targetValue === option.value ? 'opacity-100' : 'opacity-0',
                            )}
                          />
                          <span className="truncate">{option.breadcrumb || option.label}</span>
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          )}
        </>
      )}

      {/* Map Mode - VariableInput for variables or plain input */}
      {mode === 'map' && (
        <VariableInput
          value={targetValue}
          onChange={handleMapChange}
          availableContext={availableContext}
          placeholder={placeholder}
        />
      )}

      {/* Description */}
      <p className="text-xs text-slate-500">{getDescription()}</p>

      {/* Validation Error */}
      {validationError && <p className="text-xs text-red-600">{validationError}</p>}
    </div>
  );
}
