"use client";

import React from "react";
import { ComponentData, WebType, WidgetComponent } from "@/types/screen";
import { DynamicComponentRenderer } from "@/lib/registry/DynamicComponentRenderer";
import {
  Database,
  Type,
  Hash,
  List,
  AlignLeft,
  CheckSquare,
  Radio,
  Calendar,
  Code,
  Building,
  File,
} from "lucide-react";

// 컴포넌트 렌더러들 자동 등록
import "@/lib/registry/components";

interface RealtimePreviewProps {
  component: ComponentData;
  isSelected?: boolean;
  isDesignMode?: boolean; // 편집 모드 여부
  onClick?: (e?: React.MouseEvent) => void;
  onDragStart?: (e: React.DragEvent) => void;
  onDragEnd?: () => void;
  onGroupToggle?: (groupId: string) => void; // 그룹 접기/펼치기
  children?: React.ReactNode; // 그룹 내 자식 컴포넌트들
  selectedScreen?: any;
  onZoneComponentDrop?: (e: React.DragEvent, zoneId: string, layoutId: string) => void; // 존별 드롭 핸들러
  onZoneClick?: (zoneId: string) => void; // 존 클릭 핸들러
}

// 동적 위젯 타입 아이콘 (레지스트리에서 조회)
const getWidgetIcon = (widgetType: WebType | undefined): React.ReactNode => {
  if (!widgetType) return <Type className="h-3 w-3" />;

  const iconMap: Record<string, React.ReactNode> = {
    text: <span className="text-xs">Aa</span>,
    number: <Hash className="h-3 w-3" />,
    decimal: <Hash className="h-3 w-3" />,
    date: <Calendar className="h-3 w-3" />,
    datetime: <Calendar className="h-3 w-3" />,
    select: <List className="h-3 w-3" />,
    dropdown: <List className="h-3 w-3" />,
    textarea: <AlignLeft className="h-3 w-3" />,
    boolean: <CheckSquare className="h-3 w-3" />,
    checkbox: <CheckSquare className="h-3 w-3" />,
    radio: <Radio className="h-3 w-3" />,
    code: <Code className="h-3 w-3" />,
    entity: <Building className="h-3 w-3" />,
    file: <File className="h-3 w-3" />,
    email: <span className="text-xs">@</span>,
    tel: <span className="text-xs">☎</span>,
    button: <span className="text-xs">BTN</span>,
  };

  return iconMap[widgetType] || <Type className="h-3 w-3" />;
};

export const RealtimePreviewDynamic: React.FC<RealtimePreviewProps> = ({
  component,
  isSelected = false,
  isDesignMode = true, // 기본값은 편집 모드
  onClick,
  onDragStart,
  onDragEnd,
  onGroupToggle,
  children,
  selectedScreen,
  onZoneComponentDrop,
  onZoneClick,
}) => {
  const { id, type, position, size, style: componentStyle } = component;

  // 선택 상태에 따른 스타일
  const selectionStyle = isSelected
    ? {
        outline: "2px solid #3b82f6",
        outlineOffset: "2px",
        zIndex: 1000,
      }
    : {};

  // 컴포넌트 기본 스타일 - 레이아웃은 항상 맨 아래
  const baseStyle = {
    left: `${position.x}px`,
    top: `${position.y}px`,
    width: `${size?.width || 100}px`,
    height: `${size?.height || 36}px`,
    zIndex: component.type === "layout" ? 1 : position.z || 2, // 레이아웃은 z-index 1, 다른 컴포넌트는 2 이상
    ...componentStyle,
  };

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onClick?.(e);
  };

  const handleDragStart = (e: React.DragEvent) => {
    e.stopPropagation();
    onDragStart?.(e);
  };

  const handleDragEnd = () => {
    onDragEnd?.();
  };

  return (
    <div
      id={`component-${id}`}
      className="absolute cursor-pointer"
      style={{ ...baseStyle, ...selectionStyle }}
      onClick={handleClick}
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      {/* 동적 컴포넌트 렌더링 */}
      <div className="h-full w-full">
        <DynamicComponentRenderer
          component={component}
          isSelected={isSelected}
          isDesignMode={isDesignMode}
          isInteractive={!isDesignMode} // 편집 모드가 아닐 때만 인터랙티브
          onClick={onClick}
          onDragStart={onDragStart}
          onDragEnd={onDragEnd}
          children={children}
          selectedScreen={selectedScreen}
          onZoneComponentDrop={onZoneComponentDrop}
          onZoneClick={onZoneClick}
        />
      </div>

      {/* 선택된 컴포넌트 정보 표시 */}
      {isSelected && (
        <div className="absolute -top-6 left-0 rounded bg-blue-600 px-2 py-1 text-xs text-white">
          {type === "widget" && (
            <div className="flex items-center gap-1">
              {getWidgetIcon((component as WidgetComponent).widgetType)}
              {(component as WidgetComponent).widgetType || "widget"}
            </div>
          )}
          {type !== "widget" && (
            <div className="flex items-center gap-1">
              <span>{component.componentConfig?.type || type}</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// 기존 RealtimePreview와의 호환성을 위한 export
export { RealtimePreviewDynamic as RealtimePreview };
export default RealtimePreviewDynamic;
