import React, { useState } from "react";
import { Label } from "../ui/label";
import { Button } from "../ui/button";
import { Badge } from "../ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import { Plus, X } from "lucide-react";

export interface StageRule {
  id: string;
  ruleCode: string;
  ruleName: string;
  stageLevel: number;
  intermediateResultType?: 'specification' | 'item' | 'quantity' | 'value';
}

export interface MultiStageSelectorProps {
  // 선택된 단계 규칙 ID 목록
  selectedStageRuleIds: string[];
  onSelectedStageRuleIdsChange: (ids: string[]) => void;
  
  // 사용 가능한 규칙 목록
  availableRules: StageRule[];
  
  // UI 커스터마이징
  label?: string;
  placeholder?: string;
  maxSelection?: number; // 최대 선택 개수
  filterByStageLevel?: number; // 특정 단계만 필터링
  className?: string;
}

/**
 * MultiStageSelector - 다단계 규칙 선택 컴포넌트
 * 
 * 여러 개의 단계 규칙을 선택하고 관리할 수 있는 UI 컴포넌트
 * 2단계 매핑, 3단계 매핑 등에서 재사용 가능
 */
export function MultiStageSelector({
  selectedStageRuleIds,
  onSelectedStageRuleIdsChange,
  availableRules,
  label = "연결된 하위 단계 규칙",
  placeholder = "규칙 선택",
  maxSelection,
  filterByStageLevel,
  className = "",
}: MultiStageSelectorProps) {
  const [selectedRuleId, setSelectedRuleId] = useState<string>("");

  // 필터링된 규칙 목록
  const filteredRules = filterByStageLevel
    ? availableRules.filter((rule) => rule.stageLevel === filterByStageLevel)
    : availableRules;

  // 이미 선택된 규칙 제외
  const selectableRules = filteredRules.filter(
    (rule) => !selectedStageRuleIds.includes(rule.id)
  );

  // 선택된 규칙 정보
  const selectedRules = selectedStageRuleIds
    .map((id) => availableRules.find((rule) => rule.id === id))
    .filter((rule): rule is StageRule => rule !== undefined);

  // 규칙 추가
  const handleAddRule = () => {
    if (!selectedRuleId) return;
    
    if (maxSelection && selectedStageRuleIds.length >= maxSelection) {
      alert(`최대 ${maxSelection}개까지만 선택할 수 있습니다.`);
      return;
    }

    onSelectedStageRuleIdsChange([...selectedStageRuleIds, selectedRuleId]);
    setSelectedRuleId("");
  };

  // 규칙 제거
  const handleRemoveRule = (ruleId: string) => {
    onSelectedStageRuleIdsChange(
      selectedStageRuleIds.filter((id) => id !== ruleId)
    );
  };

  return (
    <div className={className}>
      <Label>{label}</Label>
      
      {/* 규칙 선택 UI */}
      <div className="flex gap-2 mb-3">
        <Select value={selectedRuleId} onValueChange={setSelectedRuleId}>
          <SelectTrigger className="flex-1">
            <SelectValue placeholder={placeholder} />
          </SelectTrigger>
          <SelectContent>
            {selectableRules.length === 0 ? (
              <div className="p-2 text-sm text-gray-500">선택 가능한 규칙이 없습니다</div>
            ) : (
              selectableRules.map((rule) => (
                <SelectItem key={rule.id} value={rule.id}>
                  [{rule.stageLevel}단계] {rule.ruleName} ({rule.ruleCode})
                </SelectItem>
              ))
            )}
          </SelectContent>
        </Select>
        
        <Button
          type="button"
          variant="outline"
          onClick={handleAddRule}
          disabled={!selectedRuleId}
        >
          <Plus className="h-4 w-4" />
        </Button>
      </div>

      {/* 선택된 규칙 목록 */}
      {selectedRules.length > 0 && (
        <div className="space-y-2">
          {selectedRules.map((rule) => (
            <div
              key={rule.id}
              className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border"
            >
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="bg-orange-50 text-orange-700">
                    {rule.stageLevel}단계
                  </Badge>
                  {rule.intermediateResultType && (
                    <Badge variant="outline">
                      {rule.intermediateResultType === 'specification' ? '규격' :
                       rule.intermediateResultType === 'item' ? '품목' :
                       rule.intermediateResultType === 'quantity' ? '수량' : '값'}
                    </Badge>
                  )}
                  <span className="font-medium">{rule.ruleName}</span>
                </div>
                <p className="text-xs text-gray-500 mt-1">{rule.ruleCode}</p>
              </div>
              
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => handleRemoveRule(rule.id)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          ))}
        </div>
      )}

      {selectedRules.length === 0 && (
        <div className="p-4 text-center text-sm text-gray-500 bg-gray-50 rounded-lg border border-dashed">
          연결된 하위 단계 규칙이 없습니다
        </div>
      )}
    </div>
  );
}
