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 { Textarea } from "./ui/textarea";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "./ui/accordion";
import { Plus, Trash2, ChevronDown, Layers, AlertCircle } from "lucide-react";
import type { FormulaRule, RangeRule, ItemMaster } from "./contexts/DataContext";
import { StageRuleInput } from "./molecules/StageRuleInput";
import { RangeRuleCard } from "./RangeRuleCard";

interface StageFormData {
  stageLevel: number;
  ruleCode: string;
  ruleName: string;
  category: string;
  inputVariable: string;
  ruleType: 'range' | 'formula' | 'fixed';
  ranges: RangeRule[];
  formula: string;
  fixedValue: number;
  unit: string;
  intermediateResultType: 'specification' | 'item' | 'quantity' | 'value';
  ruleId?: string; // 편집 모드에서 사용
}

interface MultiStageRuleFormProps {
  baseRuleCode: string;
  baseRuleName: string;
  category: string;
  availableUnits: string[];
  itemMasters: ItemMaster[];
  onSave: (stages: StageFormData[]) => void;
  onCancel: () => void;
  initialStages?: StageFormData[];
}

export function MultiStageRuleForm({
  baseRuleCode,
  baseRuleName,
  category,
  availableUnits,
  itemMasters,
  onSave,
  onCancel,
  initialStages = [],
}: MultiStageRuleFormProps) {
  const [stages, setStages] = useState<StageFormData[]>(
    initialStages.length > 0
      ? initialStages
      : [
          {
            stageLevel: 1,
            ruleCode: `${baseRuleCode}-STAGE1`,
            ruleName: `${baseRuleName} - 1단계`,
            category,
            inputVariable: '',
            ruleType: 'range',
            ranges: [],
            formula: '',
            fixedValue: 0,
            unit: '',
            intermediateResultType: 'specification',
          },
        ]
  );

  const [openItems, setOpenItems] = useState<string[]>(['stage-0']);

  const addStage = () => {
    const newStageLevel = stages.length + 1;
    setStages([
      ...stages,
      {
        stageLevel: newStageLevel,
        ruleCode: `${baseRuleCode}-STAGE${newStageLevel}`,
        ruleName: `${baseRuleName} - ${newStageLevel}단계`,
        category,
        inputVariable: '',
        ruleType: 'range',
        ranges: [],
        formula: '',
        fixedValue: 0,
        unit: '',
        intermediateResultType: 'specification',
      },
    ]);
    // 새로 추가된 단계 자동으로 열기
    setOpenItems([...openItems, `stage-${stages.length}`]);
  };

  const removeStage = (index: number) => {
    if (stages.length === 1) {
      return; // 최소 1개 단계는 유지
    }
    const newStages = stages.filter((_, i) => i !== index);
    // 단계 레벨 재정렬
    newStages.forEach((stage, i) => {
      stage.stageLevel = i + 1;
      stage.ruleCode = `${baseRuleCode}-STAGE${i + 1}`;
      stage.ruleName = `${baseRuleName} - ${i + 1}단계`;
    });
    setStages(newStages);
  };

  const updateStage = (index: number, field: keyof StageFormData, value: any) => {
    const newStages = [...stages];
    (newStages[index] as any)[field] = value;
    setStages(newStages);
  };

  const addRange = (stageIndex: number) => {
    const newStages = [...stages];
    const newRange: RangeRule = {
      id: `RANGE-${Date.now()}`,
      minValue: 0,
      maxValue: 0,
      result: '',
      items: [],
      additionalConditions: [],
    };
    newStages[stageIndex].ranges = [...newStages[stageIndex].ranges, newRange];
    setStages(newStages);
  };

  const updateRange = (stageIndex: number, rangeIndex: number, field: keyof RangeRule, value: any) => {
    const newStages = [...stages];
    const range = newStages[stageIndex].ranges[rangeIndex];
    (range as any)[field] = value;
    setStages(newStages);
  };

  const deleteRange = (stageIndex: number, rangeIndex: number) => {
    const newStages = [...stages];
    newStages[stageIndex].ranges = newStages[stageIndex].ranges.filter((_, i) => i !== rangeIndex);
    setStages(newStages);
  };

  const addRangeItem = (stageIndex: number, rangeIndex: number) => {
    const newStages = [...stages];
    const range = newStages[stageIndex].ranges[rangeIndex];
    if (!range.items) {
      range.items = [];
    }
    range.items.push({
      id: `ITEM-${Date.now()}`,
      itemCode: '',
      itemName: '',
      quantity: 0,
    });
    setStages(newStages);
  };

  const updateRangeItem = (stageIndex: number, rangeIndex: number, itemIndex: number, field: string, value: any) => {
    const newStages = [...stages];
    const range = newStages[stageIndex].ranges[rangeIndex];
    if (range.items && range.items[itemIndex]) {
      (range.items[itemIndex] as any)[field] = value;
    }
    setStages(newStages);
  };

  const deleteRangeItem = (stageIndex: number, rangeIndex: number, itemIndex: number) => {
    const newStages = [...stages];
    const range = newStages[stageIndex].ranges[rangeIndex];
    if (range.items) {
      range.items = range.items.filter((_, i) => i !== itemIndex);
    }
    setStages(newStages);
  };

  const handleSave = () => {
    // 유효성 검사
    for (let i = 0; i < stages.length; i++) {
      const stage = stages[i];
      if (!stage.ruleCode.trim()) {
        alert(`${i + 1}단계: 규칙 코드를 입력해주세요`);
        return;
      }
      if (!stage.ruleName.trim()) {
        alert(`${i + 1}단계: 규칙명을 입력해주세요`);
        return;
      }
      if (stage.ruleType === 'range' && stage.ranges.length === 0) {
        alert(`${i + 1}단계: 최소 1개 이상의 범위를 추가해주세요`);
        return;
      }
      if (stage.ruleType === 'formula' && !stage.formula.trim()) {
        alert(`${i + 1}단계: 수식을 입력해주세요`);
        return;
      }
    }

    onSave(stages);
  };

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <Card className="border-2 border-blue-500">
        <CardHeader className="bg-gradient-to-r from-blue-50 to-indigo-50">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Layers className="h-6 w-6 text-blue-600" />
              <div>
                <CardTitle>다단계 규칙 생성</CardTitle>
                <p className="text-sm text-muted-foreground mt-1">
                  여러 단계의 규칙을 한 번에 정의하고 저장할 수 있습니다
                </p>
              </div>
            </div>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={addStage}
              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>

      {/* 안내 메시지 */}
      <div className="bg-gradient-to-r from-amber-50 to-yellow-50 border-2 border-amber-300 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <AlertCircle className="h-5 w-5 text-amber-600 mt-0.5 flex-shrink-0" />
          <div>
            <p className="text-sm font-semibold text-amber-900 mb-2">💡 다단계 규칙 작성 가이드</p>
            <ul className="text-xs text-amber-800 space-y-1 ml-4 list-disc">
              <li><strong>1단계:</strong> 첫 번째 입력 변수를 기반으로 중간 결과를 도출 (예: W1 → 샤프트 규격)</li>
              <li><strong>2단계:</strong> 1단계 결과를 사용하여 최종 결과 산출 (예: 샤프트 규격 + W0 → 품목/수량)</li>
              <li><strong>3단계 이상:</strong> 필요시 더 세분화된 조건 추가 가능</li>
              <li><strong>마지막 단계:</strong> 최종 출력 결과를 반환 (품목, 수량 등)</li>
            </ul>
            <p className="text-xs text-amber-700 mt-3 bg-amber-100/80 rounded px-2 py-1">
              ⚠️ 모든 단계는 순서대로 실행되며, 이전 단계의 결과가 다음 단계의 입력이 됩니다
            </p>
          </div>
        </div>
      </div>

      {/* 단계별 아코디언 */}
      <Accordion type="multiple" value={openItems} onValueChange={setOpenItems}>
        {stages.map((stage, stageIndex) => (
          <AccordionItem key={stageIndex} value={`stage-${stageIndex}`} className="border-2 border-purple-200 rounded-lg mb-4 overflow-hidden">
            <AccordionTrigger className="px-4 py-3 hover:no-underline bg-gradient-to-r from-purple-50 to-pink-50">
              <div className="flex items-center gap-3 flex-1 text-left">
                <Badge className="bg-purple-600">
                  {stage.stageLevel}단계
                </Badge>
                <div className="flex-1">
                  <p className="font-semibold text-purple-900">{stage.ruleName || `${stage.stageLevel}단계 규칙`}</p>
                  <p className="text-xs text-purple-600">{stage.ruleCode || '규칙 코드 입력 필요'}</p>
                </div>
                <Badge variant="outline" className="bg-white">
                  {stage.ruleType === 'range' ? '📊 범위' : stage.ruleType === 'formula' ? '🧮 수식' : '📌 고정값'}
                </Badge>
                {stageIndex === stages.length - 1 && (
                  <Badge variant="outline" className="bg-green-50 text-green-700 border-green-300">
                    최종 단계
                  </Badge>
                )}
                {stages.length > 1 && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={(e) => {
                      e.stopPropagation();
                      removeStage(stageIndex);
                    }}
                    className="text-red-600 hover:text-red-700 hover:bg-red-50"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                )}
              </div>
            </AccordionTrigger>
            <AccordionContent className="px-4 py-4 bg-white">
              <div className="space-y-4">
                {/* 기본 정보 */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>규칙 코드 *</Label>
                    <Input
                      value={stage.ruleCode}
                      onChange={(e) => updateStage(stageIndex, 'ruleCode', e.target.value)}
                      placeholder={`${baseRuleCode}-STAGE${stage.stageLevel}`}
                    />
                  </div>
                  <div>
                    <Label>규칙명 *</Label>
                    <Input
                      value={stage.ruleName}
                      onChange={(e) => updateStage(stageIndex, 'ruleName', e.target.value)}
                      placeholder={`${baseRuleName} - ${stage.stageLevel}단계`}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label>기준 유형 *</Label>
                    <Select
                      value={stage.ruleType}
                      onValueChange={(v: any) => updateStage(stageIndex, 'ruleType', v)}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="range">📊 범위(Range)</SelectItem>
                        <SelectItem value="formula">🧮 수식(Formula)</SelectItem>
                        <SelectItem value="fixed">📌 고정값(Fixed)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>입력 변수</Label>
                    <Input
                      value={stage.inputVariable}
                      onChange={(e) => updateStage(stageIndex, 'inputVariable', e.target.value)}
                      placeholder={stageIndex === 0 ? "예: W1, H1, K" : "이전 단계 결과 사용"}
                    />
                  </div>
                  <div>
                    <Label>단위</Label>
                    <Select
                      value={stage.unit}
                      onValueChange={(value) => updateStage(stageIndex, 'unit', value)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="단위 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableUnits.map((unit) => (
                          <SelectItem key={unit} value={unit}>
                            {unit}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* 중간 단계 설정 */}
                {stageIndex < stages.length - 1 && (
                  <div className="bg-orange-50 border border-orange-200 rounded-lg p-3">
                    <Label className="text-sm text-orange-900 flex items-center gap-2 mb-2">
                      <Badge className="bg-orange-600">중간 단계</Badge>
                      다음 단계로 전달할 결과 타입
                    </Label>
                    <Select
                      value={stage.intermediateResultType}
                      onValueChange={(value: any) => updateStage(stageIndex, 'intermediateResultType', value)}
                    >
                      <SelectTrigger className="bg-white">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="specification">규격 (예: "4인치", "Φ30")</SelectItem>
                        <SelectItem value="item">품목 (예: 품목코드)</SelectItem>
                        <SelectItem value="quantity">수량 (예: 2개, 3EA)</SelectItem>
                        <SelectItem value="value">값 (예: 숫자)</SelectItem>
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-orange-700 mt-2">
                      이 단계의 결과가 {stage.stageLevel + 1}단계의 조건으로 사용됩니다
                    </p>
                  </div>
                )}

                <Separator />

                {/* 범위 타입 */}
                {stage.ruleType === 'range' && (
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <Label>범위 조건</Label>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => addRange(stageIndex)}
                      >
                        <Plus className="h-3 w-3 mr-1" />
                        범위 추가
                      </Button>
                    </div>
                    <div className="space-y-4">
                      {stage.ranges.map((range, rangeIndex) => (
                        <RangeRuleCard
                          key={range.id}
                          range={range}
                          index={rangeIndex}
                          isStage1={stageIndex < stages.length - 1}
                          stage1ResultType={stage.intermediateResultType}
                          itemMasters={itemMasters}
                          onUpdateRange={(idx, field, value) => updateRange(stageIndex, idx, field, value)}
                          onDeleteRange={(idx) => deleteRange(stageIndex, idx)}
                          onAddItem={(idx) => addRangeItem(stageIndex, idx)}
                          onUpdateItem={(rIdx, iIdx, field, value) => updateRangeItem(stageIndex, rIdx, iIdx, field, value)}
                          onDeleteItem={(rIdx, iIdx) => deleteRangeItem(stageIndex, rIdx, iIdx)}
                        />
                      ))}
                      {stage.ranges.length === 0 && (
                        <p className="text-sm text-gray-500 text-center py-4">
                          범위 추가 버튼을 클릭하여 범위를 등록하세요.
                        </p>
                      )}
                    </div>
                  </div>
                )}

                {/* 수식 타입 */}
                {stage.ruleType === 'formula' && (
                  <div>
                    <Label>계산 수식</Label>
                    <Textarea
                      value={stage.formula}
                      onChange={(e) => updateStage(stageIndex, 'formula', e.target.value)}
                      placeholder="예: W1 * H1 / 1000000"
                      rows={3}
                      className="font-mono"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      사용 가능한 함수: CEIL(올림), FLOOR(내림), ROUND(반올림), IF(조건, 참, 거짓)
                    </p>
                  </div>
                )}

                {/* 고정값 타입 */}
                {stage.ruleType === 'fixed' && (
                  <div>
                    <Label>고정값</Label>
                    <Input
                      type="number"
                      value={stage.fixedValue || ''}
                      onChange={(e) => updateStage(stageIndex, 'fixedValue', parseFloat(e.target.value) || 0)}
                      placeholder="예: 150"
                    />
                  </div>
                )}
              </div>
            </AccordionContent>
          </AccordionItem>
        ))}
      </Accordion>

      {/* 하단 액션 버튼 */}
      <div className="flex justify-between items-center gap-4 pt-4 border-t-2">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Layers className="h-4 w-4" />
          <span>총 {stages.length}개 단계</span>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={onCancel}>
            취소
          </Button>
          <Button onClick={handleSave} className="bg-blue-600 hover:bg-blue-700">
            전체 저장
          </Button>
        </div>
      </div>
    </div>
  );
}
