"use client";

import React from "react";
import { ComponentRendererProps } from "@/types/component";
import { TitleConfig, TitleVariant } from "./types";
import { getAdaptiveLabelColor } from "@/lib/utils/darkModeColor";
import { filterDOMProps } from "@/lib/utils/domPropsFilter";

/**
 * Title — 통합 제목/텍스트 컴포넌트
 *
 * 기존 v2-text-display + text-display(legacy) 를 흡수. variant 로 시맨틱
 * 프리셋(h1~h6/body/caption) 을 제공하며, 세부 스타일은 config 로 override.
 */

export interface TitleComponentProps extends ComponentRendererProps {
  config?: TitleConfig;
}

// variant 별 기본 스타일 (config 로 override 가능)
const VARIANT_PRESETS: Record<
  TitleVariant,
  { fontSize: string; fontWeight: string }
> = {
  h1: { fontSize: "2rem", fontWeight: "700" },
  h2: { fontSize: "1.5rem", fontWeight: "700" },
  h3: { fontSize: "1.25rem", fontWeight: "600" },
  h4: { fontSize: "1.1rem", fontWeight: "600" },
  h5: { fontSize: "1rem", fontWeight: "600" },
  h6: { fontSize: "0.875rem", fontWeight: "600" },
  body: { fontSize: "14px", fontWeight: "normal" },
  caption: { fontSize: "12px", fontWeight: "normal" },
};

export const TitleComponent: React.FC<TitleComponentProps> = ({
  component,
  isDesignMode = false,
  isSelected = false,
  onClick,
  onDragStart,
  onDragEnd,
  config,
  className,
  style,
  ...props
}) => {
  // DynamicComponentRenderer.tsx:882 가 mergedComponentConfig 를 top-level
  // props 로 spread 해서 전달. 즉 text/fontSize/color 등이 props 에 직접 있음.
  // 4곳 전부 머지해서 어느 경로든 반영되게 한다.
  const fromProps: Partial<TitleConfig> = {};
  const p = props as any;
  if (p.text !== undefined) fromProps.text = p.text;
  if (p.variant !== undefined) fromProps.variant = p.variant;
  if (p.fontSize !== undefined) fromProps.fontSize = p.fontSize;
  if (p.fontWeight !== undefined) fromProps.fontWeight = p.fontWeight;
  if (p.color !== undefined) fromProps.color = p.color;
  if (p.textAlign !== undefined) fromProps.textAlign = p.textAlign;
  if (p.lineHeight !== undefined) fromProps.lineHeight = p.lineHeight;
  if (p.letterSpacing !== undefined) fromProps.letterSpacing = p.letterSpacing;
  if (p.truncate !== undefined) fromProps.truncate = p.truncate;

  const componentConfig = {
    ...config,
    ...((component as any).config ?? {}),
    ...((component as any).componentConfig ?? {}),
    ...fromProps, // top-level spread props 가 최종 우선
  } as TitleConfig;

  const variant = componentConfig.variant;
  const preset = variant ? VARIANT_PRESETS[variant] : undefined;

  const text = componentConfig.text ?? "텍스트를 입력하세요";
  const fontSize = componentConfig.fontSize ?? preset?.fontSize ?? "14px";
  const fontWeight = componentConfig.fontWeight ?? preset?.fontWeight ?? "normal";
  const color = componentConfig.color ?? "hsl(var(--foreground))";
  const textAlign = componentConfig.textAlign ?? "left";
  const lineHeight = componentConfig.lineHeight ?? "normal";
  const letterSpacing = componentConfig.letterSpacing ?? "0";
  const truncate = componentConfig.truncate ?? false;

  const containerStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    display: "flex",
    alignItems: "center",
    justifyContent:
      textAlign === "center"
        ? "center"
        : textAlign === "right"
          ? "flex-end"
          : "flex-start",
    padding: "2px 4px",
    boxSizing: "border-box",
    position: "relative",
    ...(component as any).style,
    ...style,
  };

  if (isDesignMode) {
    containerStyle.border = `1px dashed ${isSelected ? "hsl(var(--primary))" : "hsl(var(--border))"}`;
  }

  const textStyle: React.CSSProperties = {
    fontSize,
    fontWeight,
    color: getAdaptiveLabelColor(color) ?? color,
    textAlign,
    lineHeight,
    letterSpacing,
    whiteSpace: truncate ? "nowrap" : "normal",
    overflow: truncate ? "hidden" : "visible",
    textOverflow: truncate ? "ellipsis" : "clip",
    width: "100%",
    margin: 0,
  };

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

  // DOM 에 전달하면 안 되는 React-specific props 필터링
  /* eslint-disable @typescript-eslint/no-unused-vars */
  const {
    selectedScreen: _1,
    onZoneComponentDrop: _2,
    onZoneClick: _3,
    componentConfig: _4,
    component: _5,
    isSelected: _6,
    onClick: _7,
    onDragStart: _8,
    onDragEnd: _9,
    size: _10,
    position: _11,
    style: _12,
    screenId: _13,
    tableName: _14,
    onRefresh: _15,
    onClose: _16,
    web_type: _17,
    autoGeneration: _18,
    isInteractive: _19,
    formData: _20,
    onFormDataChange: _21,
    menuId: _22,
    menuObjid: _23,
    onSave: _24,
    userId: _25,
    userName: _26,
    companyCode: _27,
    isInModal: _28,
    readonly: _29,
    originalData: _30,
    _originalData: _31,
    _initialData: _32,
    _groupedData: _33,
    allComponents: _34,
    onUpdateLayout: _35,
    selectedRows: _36,
    selectedRowsData: _37,
    onSelectedRowsChange: _38,
    sortBy: _39,
    sortOrder: _40,
    tableDisplayData: _41,
    flowSelectedData: _42,
    flowSelectedStepId: _43,
    onFlowSelectedDataChange: _44,
    onConfigChange: _45,
    refreshKey: _46,
    flowRefreshKey: _47,
    onFlowRefresh: _48,
    isPreview: _49,
    groupedData: _50,
    // ★ TitleConfig 필드 — DOM 에 spread 되면 React warning. 제외.
    text: _51,
    variant: _52,
    fontSize: _53,
    fontWeight: _54,
    color: _55,
    textAlign: _56,
    lineHeight: _57,
    letterSpacing: _58,
    truncate: _59,
    defaultValue: _60,
    placeholder: _61,
    // 기타 noise
    maxLength: _62,
    minLength: _63,
    disabled: _64,
    required: _65,
    helperText: _66,
    readonly: _67,
    ...domProps
  } = props as any;
  /* eslint-enable @typescript-eslint/no-unused-vars */

  // variant 가 h1~h6 이면 시맨틱 태그, 아니면 div.
  // React.createElement 로 생성해서 JSX.IntrinsicElements 네임스페이스 의존 회피.
  const tagName = variant && /^h[1-6]$/.test(variant) ? variant : "div";
  const textElement = React.createElement(
    tagName,
    { style: textStyle },
    text,
  );

  return (
    <div
      style={containerStyle}
      className={className}
      onClick={handleClick}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      {...filterDOMProps(domProps)}
    >
      {textElement}
    </div>
  );
};

export const TitleWrapper: React.FC<TitleComponentProps> = (props) => {
  return <TitleComponent {...props} />;
};
