import React, { useState } from "react";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
import { Plus, Trash2, Check, ChevronsUpDown, Package } from "lucide-react";
import type { AdditionalCondition, ItemMaster } from "./contexts/DataContext";
import { useData } from "./contexts/DataContext";

interface MultiConditionInputProps {
  conditions: AdditionalCondition[];
  onConditionsChange: (conditions: AdditionalCondition[]) => void;
}

export function MultiConditionInput({
  conditions,
  onConditionsChange,
}: MultiConditionInputProps) {
  
  const { itemMasters } = useData();
  const [openPopovers, setOpenPopovers] = useState<Record<string, boolean>>({});

  const addCondition = () => {
    const newCondition: AdditionalCondition = {
      id: `COND-${Date.now()}`,
      conditionSource: 'variable',
      variable: "",
      minValue: 0,
      maxValue: 100,
      conditionType: "and",
      description: ""
    };
    onConditionsChange([...conditions, newCondition]);
  };

  const updateCondition = (index: number, field: keyof AdditionalCondition, value: any) => {
    const updated = [...conditions];
    (updated[index] as any)[field] = value;
    
    // 조건 소스 변경 시 다른 필드 초기화
    if (field === 'conditionSource') {
      if (value === 'variable') {
        updated[index].itemCode = undefined;
        updated[index].itemName = undefined;
      } else if (value === 'item') {
        updated[index].variable = undefined;
        updated[index].minValue = undefined;
        updated[index].maxValue = undefined;
      }
    }
    
    onConditionsChange(updated);
  };

  const deleteCondition = (index: number) => {
    onConditionsChange(conditions.filter((_, i) => i !== index));
  };

  const togglePopover = (conditionId: string, isOpen: boolean) => {
    setOpenPopovers(prev => ({ ...prev, [conditionId]: isOpen }));
  };

  return (
    <div className="border-t mt-3 pt-3 space-y-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Label className="text-sm font-medium">추가 조건</Label>
          <Badge variant="outline" className="bg-purple-50 text-purple-700">
            복합조건
          </Badge>
        </div>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={addCondition}
          className="h-7"
        >
          <Plus className="h-3 w-3 mr-1" />
          조건 추가
        </Button>
      </div>

      {conditions.length === 0 && (
        <div className="text-center py-4 text-sm text-gray-500 bg-gray-50 rounded border border-dashed">
          조건 추가 버튼을 클릭하여 추가 조건을 등록하세요
          <p className="text-xs mt-1 text-purple-600">변수 조건 또는 품목 조건을 선택할 수 있습니다</p>
        </div>
      )}

      {conditions.map((condition, index) => (
        <div 
          key={condition.id} 
          className="pl-4 border-l-2 border-purple-300 bg-purple-50/50 p-3 rounded-r space-y-3"
        >
          <div className="flex items-center justify-between mb-2">
            <Badge 
              variant={condition.conditionType === 'and' ? 'default' : 'secondary'}
              className={condition.conditionType === 'and' ? 'bg-purple-600' : 'bg-orange-500'}
            >
              {index + 1}번 조건
            </Badge>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => deleteCondition(index)}
              className="h-7 text-red-600 hover:text-red-700 hover:bg-red-50"
            >
              <Trash2 className="h-3 w-3 mr-1" />
              삭제
            </Button>
          </div>

          <div className="grid grid-cols-2 gap-2">
            <div>
              <Label className="text-xs text-purple-700">조건 유형</Label>
              <Select
                value={condition.conditionType}
                onValueChange={(value: 'and' | 'or') => 
                  updateCondition(index, 'conditionType', value)
                }
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="and">
                    <span className="flex items-center gap-2">
                      <Badge variant="default" className="bg-purple-600 text-xs">AND</Badge>
                      <span className="text-xs">모두 만족</span>
                    </span>
                  </SelectItem>
                  <SelectItem value="or">
                    <span className="flex items-center gap-2">
                      <Badge variant="default" className="bg-orange-500 text-xs">OR</Badge>
                      <span className="text-xs">하나만 만족</span>
                    </span>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label className="text-xs text-purple-700">조건 소스</Label>
              <Select
                value={condition.conditionSource || 'variable'}
                onValueChange={(value: 'variable' | 'item') => 
                  updateCondition(index, 'conditionSource', value)
                }
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="variable">
                    <span className="flex items-center gap-2 text-xs">
                      📊 변수 (W0, H1 등)
                    </span>
                  </SelectItem>
                  <SelectItem value="item">
                    <span className="flex items-center gap-2 text-xs">
                      <Package className="h-3 w-3" />
                      품목 (모터, 부품 등)
                    </span>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 변수 기반 조건 */}
          {condition.conditionSource === 'variable' && (
            <div className="grid grid-cols-3 gap-2">
              <div>
                <Label className="text-xs text-purple-700">변수명</Label>
                <Input
                  type="text"
                  value={condition.variable || ''}
                  onChange={(e) => updateCondition(index, 'variable', e.target.value)}
                  placeholder="K, H1, weight 등"
                  className="h-8 text-sm"
                />
              </div>

              <div>
                <Label className="text-xs text-purple-700">최소값</Label>
                <Input
                  type="number"
                  value={condition.minValue || 0}
                  onChange={(e) => updateCondition(index, 'minValue', parseFloat(e.target.value) || 0)}
                  placeholder="0"
                  className="h-8 text-sm"
                />
              </div>

              <div>
                <Label className="text-xs text-purple-700">최대값</Label>
                <Input
                  type="number"
                  value={condition.maxValue || 0}
                  onChange={(e) => updateCondition(index, 'maxValue', parseFloat(e.target.value) || 0)}
                  placeholder="400"
                  className="h-8 text-sm"
                />
              </div>
            </div>
          )}

          {/* 품목 기반 조건 */}
          {condition.conditionSource === 'item' && (
            <div>
              <Label className="text-xs text-purple-700">품목 선택</Label>
              <Popover 
                open={openPopovers[condition.id] || false}
                onOpenChange={(isOpen) => togglePopover(condition.id, isOpen)}
              >
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    className="w-full justify-between h-8 text-sm"
                  >
                    {condition.itemCode ? (
                      <span className="flex items-center gap-2">
                        <Package className="h-3 w-3 text-blue-600" />
                        <span className="text-blue-700 font-medium">{condition.itemCode}</span>
                        <span className="text-gray-600">-</span>
                        <span className="text-gray-700">{condition.itemName}</span>
                      </span>
                    ) : (
                      <span className="text-gray-500">품목을 선택하세요...</span>
                    )}
                    <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[500px] p-0" align="start">
                  <Command>
                    <CommandInput placeholder="품목 검색..." className="h-9" />
                    <CommandList>
                      <CommandEmpty>검색 결과가 없습니다.</CommandEmpty>
                      <CommandGroup>
                        {itemMasters.map((item) => (
                          <CommandItem
                            key={item.id}
                            value={`${item.itemCode} ${item.itemName}`}
                            onSelect={() => {
                              updateCondition(index, 'itemCode', item.itemCode);
                              updateCondition(index, 'itemName', item.itemName);
                              togglePopover(condition.id, false);
                            }}
                          >
                            <Check
                              className={`mr-2 h-4 w-4 ${
                                condition.itemCode === item.itemCode
                                  ? "opacity-100"
                                  : "opacity-0"
                              }`}
                            />
                            <div className="flex flex-col">
                              <div className="flex items-center gap-2">
                                <span className="text-sm font-medium text-blue-600">
                                  {item.itemCode}
                                </span>
                                <span className="text-sm text-gray-700">
                                  {item.itemName}
                                </span>
                              </div>
                              {item.specification && (
                                <span className="text-xs text-gray-500">
                                  {item.specification}
                                </span>
                              )}
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
              <p className="text-xs text-purple-600 mt-1">
                💡 선택한 품목이 조건에 포함되면 이 범위가 적용됩니다
              </p>
            </div>
          )}

          <div>
            <Label className="text-xs text-purple-700">설명 (선택)</Label>
            <Input
              type="text"
              value={condition.description || ''}
              onChange={(e) => updateCondition(index, 'description', e.target.value)}
              placeholder={
                condition.conditionSource === 'item' 
                  ? "예: 모터 150K 사용 시" 
                  : "예: 중량 400kg 이하"
              }
              className="h-8 text-sm"
            />
          </div>

          {index === 0 && conditions.length > 0 && (
            <p className="text-xs text-purple-600 italic">
              💡 첫 번째 조건은 기본 범위(최소값~최대값)와 {condition.conditionType === 'and' ? 'AND' : 'OR'} 관계
            </p>
          )}
        </div>
      ))}

      {conditions.length > 0 && (
        <div className="bg-blue-50 border border-blue-200 rounded p-2">
          <p className="text-xs text-blue-800">
            <strong>💡 조건 평가:</strong>
            {conditions.map((c, i) => (
              <span key={c.id}>
                {i === 0 ? ' 기본범위 ' : ' '}
                <Badge variant={c.conditionType === 'and' ? 'default' : 'secondary'} className={`text-xs mx-1 ${c.conditionType === 'and' ? 'bg-purple-600' : 'bg-orange-500'}`}>
                  {c.conditionType.toUpperCase()}
                </Badge>
                {c.conditionSource === 'item' ? (
                  <span className="text-blue-700 font-medium">
                    품목:{c.itemCode || '미선택'}
                  </span>
                ) : (
                  <span>
                    {c.variable || '변수'} ({c.minValue}~{c.maxValue})
                  </span>
                )}
              </span>
            ))}
          </p>
        </div>
      )}
    </div>
  );
}
