/**
 * 컴포넌트 타입 유틸리티
 * 레거시와 신규 컴포넌트 시스템 모두 지원하는 타입 감지 함수들
 */

import { ComponentData } from "@/types/screen";

/**
 * 파일 컴포넌트 여부를 확인합니다
 *
 * 지원하는 타입:
 * - 레거시: type="file"
 * - 레거시: type="widget" + widgetType="file"
 * - 신규: type="component" + widgetType="file"
 * - 신규: type="component" + componentType="file-upload"
 * - 신규: type="component" + componentConfig.webType="file"
 */
export const isFileComponent = (component: ComponentData): boolean => {
  if (!component || !component.type) return false;

  return (
    component.type === "file" ||
    (component.type === "widget" && (component as any).widgetType === "file") ||
    (component.type === "component" &&
      ((component as any).widgetType === "file" || // ✅ ScreenDesigner에서 설정됨
        (component as any).componentType === "file-upload" || // ✅ ComponentRegistry ID
        (component as any).componentConfig?.webType === "file"))
  ); // ✅ componentConfig 내부
};

/**
 * 버튼 컴포넌트 여부를 확인합니다
 */
export const isButtonComponent = (component: ComponentData): boolean => {
  if (!component || !component.type) return false;

  return (
    component.type === "button" ||
    (component.type === "widget" && (component as any).widgetType === "button") ||
    (component.type === "component" &&
      ((component as any).webType === "button" || (component as any).componentType === "button"))
  );
};

/**
 * 데이터 테이블 컴포넌트 여부를 확인합니다
 */
export const isDataTableComponent = (component: ComponentData): boolean => {
  if (!component || !component.type) return false;

  return (
    component.type === "datatable" ||
    (component.type === "component" &&
      ((component as any).componentType === "datatable" || (component as any).componentType === "data-table"))
  );
};

/**
 * 위젯 컴포넌트 여부를 확인합니다
 */
export const isWidgetComponent = (component: ComponentData): boolean => {
  if (!component || !component.type) return false;
  return component.type === "widget";
};

/**
 * 컴포넌트의 웹타입을 가져옵니다 (input_type 우선)
 */
export const getComponentWebType = (component: ComponentData): string | undefined => {
  if (!component || !component.type) return undefined;

  // 파일 컴포넌트는 무조건 "file" 웹타입 반환
  if (isFileComponent(component)) {
    console.log(`🎯 파일 컴포넌트 감지 → webType: "file" 반환`, {
      componentId: component.id,
      componentType: component.type,
      widgetType: (component as any).widgetType,
      componentConfig: (component as any).componentConfig,
    });
    return "file";
  }

  // 1. componentConfig.inputType 우선 확인 (새로 추가된 컴포넌트)
  const configInputType = (component as any).componentConfig?.inputType;
  if (configInputType) {
    console.log(`✅ 컴포넌트 componentConfig.inputType 사용:`, {
      componentId: component.id,
      tableName: (component as any).tableName,
      columnName: (component as any).columnName,
      inputType: configInputType,
      componentConfig: (component as any).componentConfig,
    });
    return configInputType;
  }

  // 2. 루트 레벨 input_type 확인 (하위 호환성)
  const rootInputType = (component as any).input_type || (component as any).inputType;
  if (rootInputType) {
    console.log(`✅ 컴포넌트 루트 inputType 사용:`, {
      componentId: component.id,
      tableName: (component as any).tableName,
      columnName: (component as any).columnName,
      inputType: rootInputType,
    });
    return rootInputType;
  }

  // 3. 기본 웹타입 확인
  const webType = component.type === "widget" 
    ? (component as any).widgetType 
    : component.type === "component"
    ? (component as any).widgetType || (component as any).componentConfig?.webType
    : component.type;

  console.log(`⚠️ inputType 없음, 기본 webType 사용:`, {
    componentId: component.id,
    tableName: (component as any).tableName,
    columnName: (component as any).columnName,
    type: component.type,
    widgetType: (component as any).widgetType,
    componentConfig: (component as any).componentConfig,
    resultWebType: webType,
  });

  return webType;
};

/**
 * 컴포넌트의 실제 타입을 가져옵니다 (신규 시스템용)
 */
export const getComponentType = (component: ComponentData): string => {
  if (!component || !component.type) return "unknown";

  if (component.type === "component") {
    return (component as any).componentType || (component as any).webType || "unknown";
  }
  return component.type;
};

/**
 * 컴포넌트가 입력 가능한 컴포넌트인지 확인합니다
 */
export const isInputComponent = (component: ComponentData): boolean => {
  const inputTypes = [
    "text",
    "number",
    "email",
    "password",
    "tel",
    "url",
    "search",
    "textarea",
    "select",
    "checkbox",
    "radio",
    "date",
    "time",
    "datetime-local",
    "file",
    "code",
    "entity",
  ];

  const webType = getComponentWebType(component);
  return webType ? inputTypes.includes(webType) : false;
};

/**
 * 컴포넌트가 표시용 컴포넌트인지 확인합니다
 */
export const isDisplayComponent = (component: ComponentData): boolean => {
  const displayTypes = ["label", "text", "image", "video", "chart", "table", "datatable"];

  const webType = getComponentWebType(component);
  return webType ? displayTypes.includes(webType) : false;
};

/**
 * 컴포넌트의 필드명을 가져옵니다
 */
export const getComponentFieldName = (component: ComponentData): string => {
  if (!component) return "";
  return (component as any).columnName || component.id || "";
};

/**
 * 컴포넌트의 라벨을 가져옵니다
 */
export const getComponentLabel = (component: ComponentData): string => {
  if (!component) return "";
  return (component as any).label || (component as any).title || component.id || "";
};
