"use client";

import React from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";

// 타입 import
import { LeftPanelProps } from "../types/redesigned";

// 컴포넌트 import
import ConnectionTypeSelector from "./ConnectionTypeSelector";
import MappingDetailList from "./MappingDetailList";
import ActionSummaryPanel from "./ActionSummaryPanel";

/**
 * 📋 좌측 패널 (30% 너비)
 * - 연결 타입 선택
 * - 매핑 정보 모니터링
 * - 상세 설정 목록
 * - 액션 버튼들
 */
const LeftPanel: React.FC<LeftPanelProps> = ({ state, actions }) => {
  return (
    <div className="flex h-full flex-col overflow-hidden">
      <ScrollArea className="flex-1 p-3 pb-0">
        <div className="space-y-3 pb-3">
          {/* 0단계: 연결 타입 선택 */}
          <div>
            <h3 className="text-muted-foreground mb-2 text-sm font-medium">0단계: 연결 타입</h3>
            <ConnectionTypeSelector selectedType={state.connectionType} onTypeChange={actions.setConnectionType} />
          </div>

          {/* 외부호출이 아닐 때만 매핑과 액션 설정 표시 */}
          {state.connectionType !== "external_call" && (
            <>
              <Separator />

              {/* 매핑 상세 목록 */}
              {(() => {
                // 액션 그룹에서 모든 매핑 수집
                const allMappings = state.actionGroups.flatMap((group) =>
                  group.actions.flatMap((action) => action.fieldMappings || []),
                );

                // 기존 fieldMappings와 병합 (중복 제거)
                const combinedMappings = [...state.fieldMappings, ...allMappings];
                const uniqueMappings = combinedMappings.filter(
                  (mapping, index, arr) => arr.findIndex((m) => m.id === mapping.id) === index,
                );

                console.log("🔍 LeftPanel - 매핑 데이터 수집:", {
                  stateFieldMappings: state.fieldMappings,
                  actionGroupMappings: allMappings,
                  combinedMappings: uniqueMappings,
                });

                return (
                  uniqueMappings.length > 0 && (
                    <>
                      <div>
                        <h3 className="text-muted-foreground mb-2 text-sm font-medium">매핑 상세 목록</h3>
                        <MappingDetailList
                          mappings={uniqueMappings}
                          selectedMapping={state.selectedMapping}
                          onSelectMapping={(mappingId) => {
                            // TODO: 선택된 매핑 상태 업데이트
                          }}
                          onUpdateMapping={actions.updateMapping}
                          onDeleteMapping={actions.deleteMapping}
                        />
                      </div>

                      <Separator />
                    </>
                  )
                );
              })()}

              {/* 액션 설정 요약 */}
              <div>
                <h3 className="text-muted-foreground mb-2 text-sm font-medium">액션 설정</h3>
                <ActionSummaryPanel state={state} />
              </div>
            </>
          )}

          {/* 외부호출일 때는 간단한 설명만 표시 */}
          {state.connectionType === "external_call" && (
            <>
              <Separator />
              <div className="rounded-md bg-accent p-3">
                <h3 className="mb-1 text-sm font-medium text-primary">외부 호출 모드</h3>
                <p className="text-xs text-primary">우측 패널에서 REST API 설정을 구성하세요.</p>
              </div>
            </>
          )}
        </div>
      </ScrollArea>
    </div>
  );
};

export default LeftPanel;
