"use client";

import React from "react";
import { ComponentData, WebType } from "@/types/screen";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
// import { Checkbox } from "@/components/ui/checkbox";
// import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  Database,
  Type,
  Hash,
  List,
  AlignLeft,
  CheckSquare,
  Radio,
  Calendar,
  Code,
  Building,
  File,
  Group,
  ChevronDown,
  ChevronRight,
} from "lucide-react";

interface RealtimePreviewProps {
  component: ComponentData;
  isSelected?: boolean;
  onClick?: (e?: React.MouseEvent) => void;
  onDragStart?: (e: React.DragEvent) => void;
  onDragEnd?: () => void;
  onGroupToggle?: (groupId: string) => void; // 그룹 접기/펼치기
  children?: React.ReactNode; // 그룹 내 자식 컴포넌트들
}

// 웹 타입에 따른 위젯 렌더링
const renderWidget = (component: ComponentData) => {
  const { widgetType, label, placeholder, required, readonly, columnName, style } = component;

  // 디버깅: 실제 widgetType 값 확인
  console.log("RealtimePreview - widgetType:", widgetType, "columnName:", columnName);

  // 사용자가 테두리를 설정했는지 확인
  const hasCustomBorder = style && (style.borderWidth || style.borderStyle || style.borderColor || style.border);

  // 기본 테두리 제거 여부 결정 - Shadcn UI 기본 border 클래스를 덮어쓰기
  const borderClass = hasCustomBorder ? "!border-0" : "";

  const commonProps = {
    placeholder: placeholder || `입력하세요...`,
    disabled: readonly,
    required: required,
    className: `w-full h-full ${borderClass}`,
  };

  switch (widgetType) {
    case "text":
    case "email":
    case "tel":
      return <Input type={widgetType === "email" ? "email" : widgetType === "tel" ? "tel" : "text"} {...commonProps} />;

    case "number":
    case "decimal":
      return <Input type="number" step={widgetType === "decimal" ? "0.01" : "1"} {...commonProps} />;

    case "date":
    case "datetime":
      return <Input type={widgetType === "datetime" ? "datetime-local" : "date"} {...commonProps} />;

    case "select":
    case "dropdown":
      return (
        <select
          disabled={readonly}
          required={required}
          className={`w-full rounded-md px-3 py-2 text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none disabled:cursor-not-allowed disabled:bg-gray-100 ${
            hasCustomBorder ? "!border-0" : "border border-gray-300"
          }`}
        >
          <option value="">{placeholder || "선택하세요..."}</option>
          <option value="option1">옵션 1</option>
          <option value="option2">옵션 2</option>
          <option value="option3">옵션 3</option>
        </select>
      );

    case "textarea":
    case "text_area":
      return <Textarea {...commonProps} rows={3} />;

    case "boolean":
    case "checkbox":
      return (
        <div className="flex items-center space-x-2">
          <input
            type="checkbox"
            id={`checkbox-${component.id}`}
            disabled={readonly}
            required={required}
            className="h-4 w-4"
          />
          <Label htmlFor={`checkbox-${component.id}`} className="text-sm">
            {label || columnName}
          </Label>
        </div>
      );

    case "radio":
      return (
        <div className="space-y-2">
          <div className="flex items-center space-x-2">
            <input
              type="radio"
              id={`radio1-${component.id}`}
              name={`radio-${component.id}`}
              disabled={readonly}
              className="h-4 w-4"
            />
            <Label htmlFor={`radio1-${component.id}`} className="text-sm">
              옵션 1
            </Label>
          </div>
          <div className="flex items-center space-x-2">
            <input
              type="radio"
              id={`radio2-${component.id}`}
              name={`radio-${component.id}`}
              disabled={readonly}
              className="h-4 w-4"
            />
            <Label htmlFor={`radio2-${component.id}`} className="text-sm">
              옵션 2
            </Label>
          </div>
        </div>
      );

    case "code":
      return (
        <Textarea
          {...commonProps}
          rows={4}
          className={`w-full font-mono text-sm ${borderClass}`}
          placeholder="코드를 입력하세요..."
        />
      );

    case "entity":
      return (
        <select
          disabled={readonly}
          required={required}
          className={`w-full rounded-md px-3 py-2 text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none disabled:cursor-not-allowed disabled:bg-gray-100 ${
            hasCustomBorder ? "!border-0" : "border border-gray-300"
          }`}
        >
          <option value="">엔티티를 선택하세요...</option>
          <option value="user">사용자</option>
          <option value="product">제품</option>
          <option value="order">주문</option>
        </select>
      );

    case "file":
      return (
        <input
          type="file"
          disabled={readonly}
          required={required}
          className={`w-full rounded-md px-3 py-2 text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none disabled:cursor-not-allowed disabled:bg-gray-100 ${
            hasCustomBorder ? "!border-0" : "border border-gray-300"
          }`}
        />
      );

    default:
      return <Input type="text" {...commonProps} />;
  }
};

// 위젯 타입 아이콘
const getWidgetIcon = (widgetType: WebType | undefined) => {
  switch (widgetType) {
    case "text":
    case "email":
    case "tel":
      return <Type className="h-4 w-4 text-blue-600" />;
    case "number":
    case "decimal":
      return <Hash className="h-4 w-4 text-green-600" />;
    case "date":
    case "datetime":
      return <Calendar className="h-4 w-4 text-purple-600" />;
    case "select":
    case "dropdown":
      return <List className="h-4 w-4 text-orange-600" />;
    case "textarea":
    case "text_area":
      return <AlignLeft className="h-4 w-4 text-indigo-600" />;
    case "boolean":
    case "checkbox":
      return <CheckSquare className="h-4 w-4 text-blue-600" />;
    case "radio":
      return <Radio className="h-4 w-4 text-blue-600" />;
    case "code":
      return <Code className="h-4 w-4 text-gray-600" />;
    case "entity":
      return <Building className="h-4 w-4 text-cyan-600" />;
    case "file":
      return <File className="h-4 w-4 text-yellow-600" />;
    default:
      return <Type className="h-4 w-4 text-gray-500" />;
  }
};

export const RealtimePreview: React.FC<RealtimePreviewProps> = ({
  component,
  isSelected = false,
  onClick,
  onDragStart,
  onDragEnd,
  children,
  onGroupToggle,
}) => {
  const { type, label, tableName, columnName, widgetType, size, style } = component;

  // 사용자가 테두리를 설정했는지 확인
  const hasCustomBorder = style && (style.borderWidth || style.borderStyle || style.borderColor || style.border);

  // 기본 선택 테두리는 사용자 테두리가 없을 때만 적용
  const defaultRingClass = hasCustomBorder
    ? ""
    : isSelected
      ? "ring-opacity-50 ring-2 ring-blue-500"
      : "hover:ring-opacity-50 hover:ring-1 hover:ring-gray-300";

  // 사용자 테두리가 있을 때 선택 상태 표시를 위한 스타일
  const selectionStyle =
    hasCustomBorder && isSelected
      ? {
          boxShadow: "0 0 0 2px rgba(59, 130, 246, 0.5)", // 외부 그림자로 선택 표시
          ...style,
        }
      : style;

  // 라벨 스타일 계산
  const shouldShowLabel = component.style?.labelDisplay !== false && (component.label || component.style?.labelText);
  const labelText = component.style?.labelText || component.label || "";

  // 라벨 하단 여백 값 추출 (px 단위 숫자로 변환)
  const labelMarginBottomValue = parseInt(component.style?.labelMarginBottom || "4px", 10);

  const labelStyle: React.CSSProperties = {
    fontSize: component.style?.labelFontSize || "12px",
    color: component.style?.labelColor || "#374151",
    fontWeight: component.style?.labelFontWeight || "500",
    fontFamily: component.style?.labelFontFamily || "inherit",
    textAlign: component.style?.labelTextAlign || "left",
    backgroundColor: component.style?.labelBackgroundColor || "transparent",
    padding: component.style?.labelPadding || "0",
    borderRadius: component.style?.labelBorderRadius || "0",
  };

  return (
    <div
      className={`absolute cursor-move transition-all ${defaultRingClass}`}
      style={{
        left: `${component.position.x}px`,
        top: `${component.position.y}px`,
        width: `${size.width}px`,
        height: shouldShowLabel ? `${size.height + 20 + labelMarginBottomValue}px` : `${size.height}px`, // 라벨 공간 + 여백 추가
        zIndex: component.position.z || 1,
        ...selectionStyle,
      }}
      onClick={(e) => {
        e.stopPropagation();
        onClick?.(e);
      }}
      draggable
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      onMouseDown={(e) => {
        // 드래그 시작을 위한 마우스 다운 이벤트
        e.stopPropagation();
      }}
    >
      {/* 라벨 표시 */}
      {shouldShowLabel && (
        <div
          className="pointer-events-none absolute left-0 w-full truncate"
          style={{
            ...labelStyle,
            top: `${-20 - labelMarginBottomValue}px`, // 라벨 높이(약 20px) + 여백값만큼 위로 이동
          }}
        >
          {labelText}
          {component.required && <span style={{ color: "#f97316", marginLeft: "2px" }}>*</span>}
        </div>
      )}

      {/* 컴포넌트 내용 */}
      <div
        style={{
          width: `${size.width}px`,
          height: `${size.height}px`,
        }}
      >
        {type === "container" && (
          <div className="pointer-events-none flex h-full flex-col items-center justify-center p-2">
            <div className="flex flex-col items-center space-y-1">
              <Database className="h-6 w-6 text-blue-600" />
              <div className="text-center">
                <div className="text-xs font-medium">{label}</div>
                <div className="text-xs text-gray-500">{tableName}</div>
              </div>
            </div>
          </div>
        )}

        {type === "group" && (
          <div className="relative h-full w-full">
            {/* 그룹 박스/헤더 제거: 투명 컨테이너 */}
            <div className="absolute inset-0">{children}</div>
          </div>
        )}

        {type === "widget" && (
          <div className="flex h-full flex-col">
            {/* 위젯 본체 - 실제 웹 위젯처럼 보이도록 */}
            <div className="pointer-events-none flex-1">{renderWidget(component)}</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default RealtimePreview;
