import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Separator } from "./ui/separator";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Plus, Trash2, ArrowRight, Settings2, AlertCircle } from "lucide-react";
import type { Stage2MappingCondition, FormulaRule } from "./contexts/DataContext";

interface Stage2MappingEditorProps {
  stage1Rule: FormulaRule;
  conditions: Stage2MappingCondition[];
  onConditionsChange: (conditions: Stage2MappingCondition[]) => void;
  availableStage2Rules: FormulaRule[];
}

export function Stage2MappingEditor({
  stage1Rule,
  conditions,
  onConditionsChange,
  availableStage2Rules,
}: Stage2MappingEditorProps) {
  
  const addCondition = () => {
    const newCondition: Stage2MappingCondition = {
      id: `COND-${Date.now()}`,
      conditionType: 'exact',
      exactValue: '',
      stage2RuleId: '',
      useStage1Result: false,
      description: ''
    };
    onConditionsChange([...conditions, newCondition]);
  };

  const updateCondition = (index: number, field: keyof Stage2MappingCondition, value: any) => {
    const updated = [...conditions];
    (updated[index] as any)[field] = value;
    onConditionsChange(updated);
  };

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

  const getConditionTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      exact: '정확히 일치',
      range: '범위 조건',
      contains: '텍스트 포함',
      formula: '수식 평가'
    };
    return labels[type] || type;
  };

  return (
    <div className="space-y-4">
      {/* 헤더 영역 */}
      <Card className="border-2 border-blue-200">
        <CardHeader className="bg-blue-50">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Settings2 className="h-5 w-5 text-blue-600" />
                2단계 매핑 조건 설정
              </CardTitle>
              <p className="text-sm text-muted-foreground mt-1">
                1단계 결과값 ({stage1Rule.stage1ResultType || 'specification'})에 따라 실행할 2단계 규칙을 정의합니다
              </p>
            </div>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={addCondition}
              className="bg-blue-600 hover:bg-blue-700 text-white border-blue-600"
            >
              <Plus className="h-4 w-4 mr-1" />
              조건 추가
            </Button>
          </div>
        </CardHeader>
      </Card>

      {/* 안내 메시지 */}
      {conditions.length === 0 && (
        <div className="text-center py-8 text-sm text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
          <Settings2 className="h-12 w-12 mx-auto mb-3 text-gray-400" />
          <p className="font-medium text-gray-700">등록된 조건이 없습니다</p>
          <p className="text-xs mt-1">조건 추가 버튼을 클릭하여 2단계 매핑 조건을 등록하세요</p>
        </div>
      )}

      {/* 조건 리스트 */}
      {conditions.map((condition, index) => (
        <Card key={condition.id} className="border-2 border-blue-200">
          <CardHeader className="bg-gradient-to-r from-blue-50 to-blue-100/50">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Badge variant="default" className="bg-blue-600">
                  조건 {index + 1}
                </Badge>
                <ArrowRight className="h-4 w-4 text-blue-500" />
                <Badge variant="outline" className="bg-white border-blue-300 text-blue-700">
                  {getConditionTypeLabel(condition.conditionType)}
                </Badge>
              </div>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => deleteCondition(index)}
                className="text-red-600 hover:text-red-700 hover:bg-red-50"
              >
                <Trash2 className="h-4 w-4 mr-1" />
                삭제
              </Button>
            </div>
          </CardHeader>
          
          <CardContent className="pt-6 space-y-6">
            {/* 조건 타입 및 실행 규칙 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label className="text-sm text-muted-foreground">조건 타입</Label>
                <Select
                  value={condition.conditionType}
                  onValueChange={(value: any) => 
                    updateCondition(index, 'conditionType', value)
                  }
                >
                  <SelectTrigger className="bg-white mt-1">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="exact">정확히 일치 (예: "4인치")</SelectItem>
                    <SelectItem value="range">범위 조건 (예: 1000~2000)</SelectItem>
                    <SelectItem value="contains">텍스트 포함 (예: "샤프트")</SelectItem>
                    <SelectItem value="formula">수식 평가 (고급)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label className="text-sm text-muted-foreground">실행할 2단계 규칙 <span className="text-red-500">*</span></Label>
                <Select
                  value={condition.stage2RuleId}
                  onValueChange={(value) => 
                    updateCondition(index, 'stage2RuleId', value)
                  }
                >
                  <SelectTrigger className="bg-white mt-1">
                    <SelectValue placeholder="2단계 규칙을 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableStage2Rules.map((rule) => (
                      <SelectItem key={rule.id} value={rule.id}>
                        {rule.ruleName} ({rule.ruleCode})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Separator />

            {/* 조건별 입력 필드 */}
            <div>
              <Label className="text-sm text-muted-foreground mb-2 block">조건 상세 설정</Label>
              
              {condition.conditionType === 'exact' && (
                <div>
                  <Label className="text-sm">일치할 값 <span className="text-red-500">*</span></Label>
                  <Input
                    type="text"
                    value={condition.exactValue || ''}
                    onChange={(e) => updateCondition(index, 'exactValue', e.target.value)}
                    placeholder="예: 4인치, Φ30, 5.5mm"
                    className="mt-1"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    1단계 결과값과 정확히 일치하는 값을 입력하세요
                  </p>
                </div>
              )}

              {condition.conditionType === 'range' && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label className="text-sm">최소값 <span className="text-red-500">*</span></Label>
                    <Input
                      type="number"
                      value={condition.minValue || 0}
                      onChange={(e) => updateCondition(index, 'minValue', parseFloat(e.target.value) || 0)}
                      placeholder="1000"
                      className="mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-sm">최대값 <span className="text-red-500">*</span></Label>
                    <Input
                      type="number"
                      value={condition.maxValue || 0}
                      onChange={(e) => updateCondition(index, 'maxValue', parseFloat(e.target.value) || 0)}
                      placeholder="2000"
                      className="mt-1"
                    />
                  </div>
                  <div className="col-span-2">
                    <p className="text-xs text-muted-foreground">
                      {condition.minValue || 0} ≤ 1단계 결과 ≤ {condition.maxValue || 0} 범위에 해당하는 경우 실행됩니다
                    </p>
                  </div>
                </div>
              )}

              {condition.conditionType === 'contains' && (
                <div>
                  <Label className="text-sm">포함할 텍스트 <span className="text-red-500">*</span></Label>
                  <Input
                    type="text"
                    value={condition.containsText || ''}
                    onChange={(e) => updateCondition(index, 'containsText', e.target.value)}
                    placeholder="예: 샤프트, 철재"
                    className="mt-1"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    1단계 결과값에 해당 텍스트가 포함되어 있는지 확인합니다
                  </p>
                </div>
              )}

              {condition.conditionType === 'formula' && (
                <div>
                  <Label className="text-sm">수식 (stage1Result 사용) <span className="text-red-500">*</span></Label>
                  <Input
                    type="text"
                    value={condition.formula || ''}
                    onChange={(e) => updateCondition(index, 'formula', e.target.value)}
                    placeholder="예: stage1Result > 1000 && stage1Result < 2000"
                    className="mt-1 font-mono"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    JavaScript 수식을 사용하여 고급 조건을 정의할 수 있습니다
                  </p>
                </div>
              )}
            </div>

            <Separator />

            {/* 1단계 결과 사용 옵션 */}
            <div className="space-y-3">
              <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border">
                <input
                  type="checkbox"
                  id={`use-result-${condition.id}`}
                  checked={condition.useStage1Result || false}
                  onChange={(e) => updateCondition(index, 'useStage1Result', e.target.checked)}
                  className="h-4 w-4 rounded border-gray-300"
                />
                <Label htmlFor={`use-result-${condition.id}`} className="text-sm cursor-pointer flex-1">
                  1단계 결과를 2단계 규칙의 입력값으로 전달
                </Label>
              </div>

              {condition.useStage1Result && (
                <div>
                  <Label className="text-sm">2단계 입력 변수명</Label>
                  <Input
                    type="text"
                    value={condition.stage2InputVariable || ''}
                    onChange={(e) => updateCondition(index, 'stage2InputVariable', e.target.value)}
                    placeholder="예: diameter, size, spec"
                    className="mt-1"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    2단계 규칙에서 사용할 변수명을 지정하세요
                  </p>
                </div>
              )}
            </div>

            <Separator />

            {/* 설명 */}
            <div>
              <Label className="text-sm text-muted-foreground">설명 (선택)</Label>
              <Input
                type="text"
                value={condition.description || ''}
                onChange={(e) => updateCondition(index, 'description', e.target.value)}
                placeholder="예: 4인치 샤프트는 RULE-059 사용"
                className="mt-1"
              />
            </div>

            {/* 조건 미리보기 */}
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div className="flex items-start gap-2">
                <AlertCircle className="h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0" />
                <div className="text-sm text-blue-900 flex-1">
                  <p className="font-medium mb-1">조건 미리보기</p>
                  <p className="text-xs">
                    <strong>조건:</strong>{' '}
                    {condition.conditionType === 'exact' && `1단계 결과 = "${condition.exactValue || '값 입력 필요'}"`}
                    {condition.conditionType === 'range' && `${condition.minValue || 0} ≤ 1단계 결과 ≤ ${condition.maxValue || 0}`}
                    {condition.conditionType === 'contains' && `1단계 결과에 "${condition.containsText || '텍스트 입력 필요'}" 포함`}
                    {condition.conditionType === 'formula' && `${condition.formula || '수식 입력 필요'}`}
                  </p>
                  <p className="text-xs mt-1">
                    <strong>실행:</strong>{' '}
                    {availableStage2Rules.find(r => r.id === condition.stage2RuleId)?.ruleName || '2단계 규칙 선택 필요'}
                  </p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      ))}

      {/* 평가 순서 안내 */}
      {conditions.length > 0 && (
        <Card className="bg-blue-50 border-2 border-blue-200">
          <CardContent className="pt-4">
            <div className="flex items-start gap-2">
              <AlertCircle className="h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-sm font-medium text-blue-900">평가 순서</p>
                <p className="text-sm text-blue-800 mt-1">
                  조건은 위에서 아래로 순차적으로 평가되며, 첫 번째로 일치하는 조건의 2단계 규칙이 실행됩니다.
                </p>
                <p className="text-xs text-blue-700 mt-2">
                  💡 더 구체적인 조건을 위쪽에 배치하는 것을 권장합니다.
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
