import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { 
  ArrowRight, 
  GitBranch, 
  Layers, 
  ChevronRight, 
  Info,
  Maximize2,
  Lightbulb,
  BookOpen
} from "lucide-react";
import type { FormulaRule } from "./contexts/DataContext";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "./ui/dialog";

interface RuleDependencyVisualizerProps {
  rules: FormulaRule[];
  onEditMultiStage?: (firstStageRule: FormulaRule) => void;
}

export function RuleDependencyVisualizer({ 
  rules, 
  onEditMultiStage 
}: RuleDependencyVisualizerProps) {
  const [expandedChains, setExpandedChains] = useState<Set<string>>(new Set());
  const [isFullScreen, setIsFullScreen] = useState(false);

  // 다단계 규칙 체인 찾기 (첫 번째 단계만)
  const findRuleChains = () => {
    const chains: FormulaRule[][] = [];
    const processedRules = new Set<string>();

    rules.forEach(rule => {
      // 이미 처리된 규칙이거나 중간/하위 단계면 스킵
      if (processedRules.has(rule.id)) return;
      if (rule.parentStageRuleId || rule.stage1RuleId) return;

      // 다음 단계가 있는 경우만 체인으로 간주
      if (!rule.childStageRuleIds?.length && !rule.stage2RuleIds?.length) return;

      // 체인 구성
      const chain: FormulaRule[] = [];
      let currentRule: FormulaRule | undefined = rule;

      while (currentRule) {
        chain.push(currentRule);
        processedRules.add(currentRule.id);

        // 다음 단계 찾기
        const nextRuleId = currentRule.childStageRuleIds?.[0] || currentRule.stage2RuleIds?.[0];
        if (nextRuleId) {
          currentRule = rules.find(r => r.id === nextRuleId);
        } else {
          break;
        }
      }

      if (chain.length > 1) {
        chains.push(chain);
      }
    });

    return chains;
  };

  const ruleChains = findRuleChains();

  const toggleChain = (chainId: string) => {
    const newExpanded = new Set(expandedChains);
    if (newExpanded.has(chainId)) {
      newExpanded.delete(chainId);
    } else {
      newExpanded.add(chainId);
    }
    setExpandedChains(newExpanded);
  };

  const getRuleTypeIcon = (ruleType: string) => {
    switch (ruleType) {
      case 'range': return '📊';
      case 'formula': return '🧮';
      case 'fixed': return '📌';
      default: return '📋';
    }
  };

  const getRuleTypeColor = (ruleType: string) => {
    switch (ruleType) {
      case 'range': return 'bg-purple-50 text-purple-700 border-purple-200';
      case 'formula': return 'bg-blue-50 text-blue-700 border-blue-200';
      case 'fixed': return 'bg-green-50 text-green-700 border-green-200';
      default: return 'bg-gray-50 text-gray-700 border-gray-200';
    }
  };

  const getResultTypeLabel = (resultType?: string) => {
    switch (resultType) {
      case 'specification': return '규격';
      case 'item': return '품목';
      case 'quantity': return '수량';
      case 'value': return '값';
      default: return '결과';
    }
  };

  const VisualizerContent = () => (
    <div className="space-y-6">
      {/* 용어 설명 가이드 */}
      <div className="p-4 bg-gradient-to-r from-amber-50 to-yellow-50 border-2 border-amber-300 rounded-lg">
        <div className="flex items-start gap-3">
          <BookOpen className="h-5 w-5 text-amber-700 mt-0.5 flex-shrink-0" />
          <div className="flex-1">
            <h4 className="font-semibold text-amber-900 mb-2">📖 용어 설명</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
              <div className="bg-white/60 rounded p-3">
                <p className="font-medium text-amber-900 mb-1">산정 기준 (FormulaRule)</p>
                <p className="text-xs text-amber-800">
                  자동 계산을 위한 <strong>개별 규칙 한 개</strong>를 의미합니다. 
                  예: "케이스 사이즈 → 보강 갯수" 규칙 1개
                </p>
              </div>
              <div className="bg-white/60 rounded p-3">
                <p className="font-medium text-amber-900 mb-1">규칙 체인 (Rule Chain)</p>
                <p className="text-xs text-amber-800">
                  <strong>여러 산정 기준</strong>이 연결되어 순차적으로 실행되는 흐름입니다. 
                  예: 1단계 → 2단계 → 3단계
                </p>
              </div>
              <div className="bg-white/60 rounded p-3">
                <p className="font-medium text-amber-900 mb-1">규칙 타입</p>
                <p className="text-xs text-amber-800">
                  📊 <strong>범위:</strong> 입력값 구간별로 결과 반환 | 
                  🧮 <strong>수식:</strong> 계산식으로 결과 도출 | 
                  📌 <strong>고정값:</strong> 항상 동일한 값
                </p>
              </div>
              <div className="bg-white/60 rounded p-3">
                <p className="font-medium text-amber-900 mb-1">단계 구분</p>
                <p className="text-xs text-amber-800">
                  <strong>1단계:</strong> 시작점 | 
                  <strong>중간 단계:</strong> 데이터 전달 | 
                  <strong>최종 단계:</strong> 품목/수량 결정
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 빠른 사용 가이드 */}
      <div className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg">
        <div className="flex items-start gap-3">
          <Lightbulb className="h-5 w-5 text-green-600 mt-0.5 flex-shrink-0" />
          <div className="flex-1">
            <h4 className="font-semibold text-green-900 mb-2">🚀 빠른 시작 가이드</h4>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-3 text-sm text-green-800">
              <div>
                <p className="font-medium mb-1">📝 단순 산정 기준</p>
                <ol className="text-xs space-y-1 ml-4 list-decimal">
                  <li>기준 등록 버튼 클릭</li>
                  <li>기준 유형 선택</li>
                  <li>조건 입력 후 등록</li>
                </ol>
              </div>
              <div className="bg-blue-50 rounded p-2">
                <p className="font-medium mb-1 text-blue-900">🎯 다단계 규칙 체인</p>
                <ol className="text-xs space-y-1 ml-4 list-decimal text-blue-800">
                  <li><strong>다단계 규칙 생성</strong></li>
                  <li>한 화면에서 모든 단계 작성</li>
                  <li>전체 저장 완료!</li>
                </ol>
              </div>
              <div className="bg-purple-50 rounded p-2">
                <p className="font-medium mb-1 text-purple-900">💾 템플릿 활용</p>
                <ol className="text-xs space-y-1 ml-4 list-decimal text-purple-800">
                  <li><strong>템플릿 저장</strong></li>
                  <li>재사용 가능</li>
                  <li>파일 공유 가능</li>
                </ol>
              </div>
              <div>
                <p className="font-medium mb-1">🔧 빠른 복사</p>
                <ol className="text-xs space-y-1 ml-4 list-decimal">
                  <li><strong>복사</strong> 버튼</li>
                  <li>코드/이름 수정</li>
                  <li>유사 규칙 생성</li>
                </ol>
              </div>
            </div>
            <p className="text-xs text-green-700 mt-3 bg-white/60 rounded px-2 py-1">
              ✨ <strong>신기능:</strong> 다단계 규칙 한 번에 작성 · 템플릿 저장/불러오기 · 규칙 간 의존성 시각화 · 일괄 수정 기능
            </p>
          </div>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="border-2 border-blue-200 bg-gradient-to-br from-blue-50 to-indigo-50">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">총 규칙 체인</p>
                <p className="text-3xl font-bold text-blue-600">{ruleChains.length}</p>
              </div>
              <GitBranch className="h-10 w-10 text-blue-400" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-2 border-purple-200 bg-gradient-to-br from-purple-50 to-pink-50">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">총 연결 단계</p>
                <p className="text-3xl font-bold text-purple-600">
                  {ruleChains.reduce((sum, chain) => sum + chain.length, 0)}
                </p>
              </div>
              <Layers className="h-10 w-10 text-purple-400" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-2 border-orange-200 bg-gradient-to-br from-orange-50 to-amber-50">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">최대 단계 수</p>
                <p className="text-3xl font-bold text-orange-600">
                  {ruleChains.length > 0 ? Math.max(...ruleChains.map(c => c.length)) : 0}
                </p>
              </div>
              <Layers className="h-10 w-10 text-orange-400" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 안내 메시지 */}
      {ruleChains.length === 0 && (
        <Card className="border-2 border-gray-200">
          <CardContent className="pt-6">
            <div className="text-center py-8">
              <GitBranch className="h-16 w-16 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-500 mb-2">다단계 규칙 체인이 없습니다</p>
              <p className="text-sm text-gray-400">
                "다단계 규칙 생성" 버튼으로 새로운 규칙 체인을 만들어보세요
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 규칙 체인 목록 */}
      {ruleChains.map((chain, chainIndex) => {
        const chainId = chain[0].id;
        const isExpanded = expandedChains.has(chainId);

        return (
          <Card key={chainId} className="border-2 border-indigo-200 overflow-hidden">
            <CardHeader className="bg-gradient-to-r from-indigo-50 to-purple-50 pb-3">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3 flex-1">
                  <Badge className="bg-indigo-600 text-white px-3 py-1">
                    체인 {chainIndex + 1}
                  </Badge>
                  <div className="flex-1">
                    <CardTitle className="text-base">{chain[0].ruleName}</CardTitle>
                    <p className="text-xs text-gray-500 mt-1">{chain[0].ruleCode}</p>
                  </div>
                  <Badge variant="outline" className="bg-white">
                    {chain.length}단계
                  </Badge>
                </div>
                <div className="flex gap-2">
                  {onEditMultiStage && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => onEditMultiStage(chain[0])}
                      className="border-purple-300 hover:bg-purple-50"
                    >
                      <Layers className="h-3 w-3 mr-1" />
                      일괄 수정
                    </Button>
                  )}
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => toggleChain(chainId)}
                  >
                    <ChevronRight 
                      className={`h-4 w-4 transition-transform ${isExpanded ? 'rotate-90' : ''}`} 
                    />
                  </Button>
                </div>
              </div>
            </CardHeader>

            {isExpanded && (
              <CardContent className="pt-4">
                <div className="space-y-3">
                  {chain.map((rule, stageIndex) => (
                    <div key={rule.id}>
                      {/* 단계 카드 */}
                      <div className="flex items-start gap-3">
                        {/* 단계 번호 */}
                        <div className="flex flex-col items-center gap-2">
                          <div className="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-500 to-purple-500 text-white flex items-center justify-center font-bold shadow-lg">
                            {stageIndex + 1}
                          </div>
                          {stageIndex < chain.length - 1 && (
                            <div className="w-0.5 h-12 bg-gradient-to-b from-indigo-300 to-purple-300" />
                          )}
                        </div>

                        {/* 규칙 정보 */}
                        <div className="flex-1">
                          <Card className={`border-2 ${
                            stageIndex === chain.length - 1 
                              ? 'border-green-300 bg-gradient-to-r from-green-50 to-emerald-50' 
                              : 'border-orange-300 bg-gradient-to-r from-orange-50 to-amber-50'
                          }`}>
                            <CardContent className="p-4">
                              <div className="flex items-start justify-between mb-2">
                                <div className="flex-1">
                                  <div className="flex items-center gap-2 mb-1">
                                    <Badge variant="outline" className={getRuleTypeColor(rule.ruleType)}>
                                      {getRuleTypeIcon(rule.ruleType)} {
                                        rule.ruleType === 'range' ? '범위' :
                                        rule.ruleType === 'formula' ? '수식' : '고정값'
                                      }
                                    </Badge>
                                    {stageIndex === chain.length - 1 ? (
                                      <Badge className="bg-green-600">최종 단계</Badge>
                                    ) : (
                                      <Badge className="bg-orange-600">
                                        중간 단계 → {getResultTypeLabel(rule.intermediateResultType || rule.stage1ResultType)}
                                      </Badge>
                                    )}
                                  </div>
                                  <h4 className="font-semibold text-sm">{rule.ruleName}</h4>
                                  <p className="text-xs text-gray-500">{rule.ruleCode}</p>
                                </div>
                              </div>

                              <div className="grid grid-cols-2 gap-3 mt-3 text-xs">
                                <div>
                                  <span className="text-gray-500">입력 변수:</span>
                                  <Badge variant="outline" className="ml-1">
                                    {rule.inputVariable || 'N/A'}
                                  </Badge>
                                </div>
                                <div>
                                  <span className="text-gray-500">단위:</span>
                                  <Badge variant="outline" className="ml-1">
                                    {rule.unit || 'N/A'}
                                  </Badge>
                                </div>
                              </div>

                              {/* 범위 개수 표시 */}
                              {rule.ruleType === 'range' && rule.ranges && (
                                <div className="mt-3 pt-3 border-t">
                                  <span className="text-xs text-gray-600">
                                    📊 {rule.ranges.length}개 범위 조건
                                  </span>
                                </div>
                              )}

                              {/* 수식 표시 */}
                              {rule.ruleType === 'formula' && rule.formula && (
                                <div className="mt-3 pt-3 border-t">
                                  <code className="text-xs bg-white px-2 py-1 rounded border block">
                                    {rule.formula}
                                  </code>
                                </div>
                              )}
                            </CardContent>
                          </Card>
                        </div>
                      </div>

                      {/* 연결 화살표 */}
                      {stageIndex < chain.length - 1 && (
                        <div className="flex items-center gap-2 my-2 ml-14 text-xs text-gray-500">
                          <ArrowRight className="h-4 w-4 text-indigo-400" />
                          <span className="bg-indigo-50 px-2 py-0.5 rounded border border-indigo-200">
                            {getResultTypeLabel(rule.intermediateResultType || rule.stage1ResultType)} 전달
                          </span>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </CardContent>
            )}
          </Card>
        );
      })}
    </div>
  );

  return (
    <>
      {/* 통합 버전 */}
      <Card className="border-2 border-indigo-300">
        <CardHeader className="bg-gradient-to-r from-indigo-50 to-purple-50">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <GitBranch className="h-6 w-6 text-indigo-600" />
              <div>
                <CardTitle>규칙 의존성 시각화 & 사용 가이드</CardTitle>
                <p className="text-sm text-muted-foreground mt-1">
                  다단계 규칙의 연결 관계를 한눈에 확인하고 빠르게 시작하세요
                </p>
              </div>
            </div>
            <Dialog open={isFullScreen} onOpenChange={setIsFullScreen}>
              <DialogTrigger asChild>
                {/* 전체화면 버튼 제거됨 */}
              </DialogTrigger>
              <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle className="flex items-center gap-2">
                    <GitBranch className="h-5 w-5" />
                    규칙 의존성 시각화 - 전체화면
                  </DialogTitle>
                </DialogHeader>
                <div className="mt-4">
                  <VisualizerContent />
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent className="pt-6">
          <VisualizerContent />
        </CardContent>
      </Card>
    </>
  );
}