import { useState } from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Plus, X } from "lucide-react";

interface OptionsManagerProps {
  options: string[];
  onChange: (options: string[]) => void;
  label?: string;
  placeholder?: string;
  disabled?: boolean;
}

/**
 * 품목기준관리에서 드롭다운 옵션을 관리하는 컴포넌트
 * 옵션을 태그 형식으로 추가/삭제할 수 있습니다
 */
export function OptionsManager({
  options,
  onChange,
  label = "옵션 목록",
  placeholder = "옵션 입력 후 Enter 또는 추가 버튼 클릭",
  disabled = false
}: OptionsManagerProps) {
  const [newOption, setNewOption] = useState("");

  const handleAddOption = () => {
    const trimmedOption = newOption.trim();
    if (trimmedOption && !options.includes(trimmedOption)) {
      onChange([...options, trimmedOption]);
      setNewOption("");
    }
  };

  const handleRemoveOption = (optionToRemove: string) => {
    onChange(options.filter(opt => opt !== optionToRemove));
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddOption();
    }
  };

  return (
    <div className="space-y-3">
      <Label>{label}</Label>
      
      {/* 입력 필드 */}
      <div className="flex gap-2">
        <Input
          value={newOption}
          onChange={(e) => setNewOption(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder={placeholder}
          disabled={disabled}
        />
        <Button
          type="button"
          onClick={handleAddOption}
          disabled={disabled || !newOption.trim()}
          size="sm"
          className="flex-shrink-0"
        >
          <Plus className="w-4 h-4 mr-1" />
          추가
        </Button>
      </div>

      {/* 옵션 목록 */}
      {options.length > 0 && (
        <div className="flex flex-wrap gap-2 p-3 border rounded-md bg-muted/30">
          {options.map((option, index) => (
            <Badge
              key={index}
              variant="secondary"
              className="text-sm py-1.5 px-3 flex items-center gap-2"
            >
              <span>{option}</span>
              {!disabled && (
                <button
                  type="button"
                  onClick={() => handleRemoveOption(option)}
                  className="hover:bg-destructive/20 rounded-full p-0.5 transition-colors"
                  title="삭제"
                >
                  <X className="w-3 h-3" />
                </button>
              )}
            </Badge>
          ))}
        </div>
      )}

      {options.length === 0 && !disabled && (
        <p className="text-sm text-muted-foreground">
          아직 옵션이 없습니다. 위 입력 필드에서 옵션을 추가해주세요.
        </p>
      )}

      <p className="text-xs text-muted-foreground">
        * 품목관리에서 이 항목의 드롭다운에 표시될 값들입니다
      </p>
    </div>
  );
}
