"use client";

import React from "react";
import { ComponentRendererProps } from "@/types/component";
import { ImageDisplayConfig } from "./types";
import { getAdaptiveLabelColor } from "@/lib/utils/darkModeColor";

export interface ImageDisplayComponentProps extends ComponentRendererProps {
  config?: ImageDisplayConfig;
}

/**
 * ImageDisplay 컴포넌트
 * image-display 컴포넌트입니다
 */
export const ImageDisplayComponent: React.FC<ImageDisplayComponentProps> = ({
  component,
  isDesignMode = false,
  isSelected = false,
  onClick,
  onDragStart,
  onDragEnd,
  config,
  className,
  style,
  ...props
}) => {
  const componentConfig = {
    ...config,
    ...component.config,
  } as ImageDisplayConfig;

  const objectFit = componentConfig.objectFit || "contain";
  const altText = componentConfig.altText || "이미지";
  const borderRadius = componentConfig.borderRadius ?? 8;
  const showBorder = componentConfig.showBorder ?? true;
  const backgroundColor = componentConfig.backgroundColor || "#f9fafb";
  const placeholder = componentConfig.placeholder || "이미지 없음";

  const imageSrc = component.value || componentConfig.imageUrl || "";

  const componentStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    ...component.style,
    ...style,
    width: "100%",
  };

  if (isDesignMode) {
    componentStyle.border = "1px dashed #cbd5e1";
    componentStyle.borderColor = isSelected ? "#3b82f6" : "#cbd5e1";
  }

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

  // DOM에 전달하면 안 되는 React-specific props 필터링
  const {
    selectedScreen,
    onZoneComponentDrop,
    onZoneClick,
    componentConfig: _componentConfig,
    component: _component,
    isSelected: _isSelected,
    onClick: _onClick,
    onDragStart: _onDragStart,
    onDragEnd: _onDragEnd,
    size: _size,
    position: _position,
    style: _style,
    screenId: _screenId,
    tableName: _tableName,
    onRefresh: _onRefresh,
    onClose: _onClose,
    ...domProps
  } = props;

  return (
    <div style={componentStyle} className={className} {...domProps}>
      {/* 라벨 렌더링 */}
      {component.label && (component.style?.labelDisplay ?? true) && (
        <label
          style={{
            position: "absolute",
            top: "-25px",
            left: "0px",
            fontSize: component.style?.labelFontSize || "14px",
            color: getAdaptiveLabelColor(component.style?.labelColor),
            fontWeight: "500",
          }}
        >
          {component.label}
          {(component.required || componentConfig.required) && (
            <span style={{ color: "#ef4444" }}>*</span>
          )}
        </label>
      )}

      <div
        style={{
          width: "100%",
          height: "100%",
          border: showBorder ? "1px solid #d1d5db" : "none",
          borderRadius: `${borderRadius}px`,
          overflow: "hidden",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          backgroundColor,
          transition: "all 0.2s ease-in-out",
          boxShadow: showBorder ? "0 1px 2px 0 rgba(0, 0, 0, 0.05)" : "none",
          opacity: componentConfig.disabled ? 0.5 : 1,
          cursor: componentConfig.disabled ? "not-allowed" : "default",
        }}
        onMouseEnter={(e) => {
          if (!componentConfig.disabled) {
            if (showBorder) {
              e.currentTarget.style.borderColor = "#f97316";
            }
            e.currentTarget.style.boxShadow = "0 4px 6px -1px rgba(0, 0, 0, 0.1)";
          }
        }}
        onMouseLeave={(e) => {
          if (showBorder) {
            e.currentTarget.style.borderColor = "#d1d5db";
          }
          e.currentTarget.style.boxShadow = showBorder
            ? "0 1px 2px 0 rgba(0, 0, 0, 0.05)"
            : "none";
        }}
        onClick={handleClick}
        onDragStart={onDragStart}
        onDragEnd={onDragEnd}
      >
        {imageSrc ? (
          <img
            src={imageSrc}
            alt={altText}
            style={{
              maxWidth: "100%",
              maxHeight: "100%",
              objectFit,
            }}
            onError={(e) => {
              (e.target as HTMLImageElement).style.display = "none";
              if (e.target?.parentElement) {
                e.target.parentElement.innerHTML = `
                  <div style="display: flex; flex-direction: column; align-items: center; gap: 8px; color: #6b7280; font-size: 14px;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M10.41 10.41a2 2 0 1 1-2.83-2.83"/><line x1="13.5" y1="13.5" x2="6" y2="21"/><line x1="18" y1="12" x2="21" y2="15"/><path d="M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59"/><path d="M21 15V5a2 2 0 0 0-2-2H9"/></svg>
                    <div>이미지 로드 실패</div>
                  </div>
                `;
              }
            }}
          />
        ) : (
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              gap: "8px",
              color: "#6b7280",
              fontSize: "14px",
            }}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="32"
              height="32"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
              <circle cx="8.5" cy="8.5" r="1.5" />
              <polyline points="21 15 16 10 5 21" />
            </svg>
            <div>{placeholder}</div>
          </div>
        )}
      </div>
    </div>
  );
};

/**
 * ImageDisplay 래퍼 컴포넌트
 */
export const ImageDisplayWrapper: React.FC<ImageDisplayComponentProps> = (props) => {
  return <ImageDisplayComponent {...props} />;
};
