"use client";

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

/**
 * Divider — 통합 구분선 컴포넌트
 *
 * 기존 v2-divider-line, v2-split-line, divider-line(legacy) 을 흡수한
 * 통합 컴포넌트. config.orientation 으로 가로/세로를 분기하고 config.text 가
 * 있으면 가운데 텍스트 라벨을 표시한다.
 *
 * 통합 범위:
 *   - v2-divider-line: 가로 구분선 + 텍스트 옵션 → orientation='horizontal'
 *   - v2-split-line:   세로 분할선 (드래그는 다음 단계) → orientation='vertical'
 *   - divider-line:    legacy v2-divider-line 과 동일 → 삭제 대상
 */

export interface DividerComponentProps extends ComponentRendererProps {
  config?: DividerConfig;
}

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

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

  const orientation: "horizontal" | "vertical" =
    componentConfig.orientation ?? "horizontal";
  const color = componentConfig.color || "hsl(var(--border))";
  const textColor = componentConfig.textColor || "hsl(var(--muted-foreground))";
  const thickness = componentConfig.thickness || "1px";
  const lineStyle = componentConfig.lineStyle || "solid";
  const rounded = componentConfig.rounded ?? false;
  const text = componentConfig.text;

  const containerStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
    ...(component as any).style,
    ...style,
  };

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

  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,
    // ★ DividerConfig 필드 — DOM 에 spread 되면 React warning. 제외.
    orientation: _51,
    text: _52,
    color: _53,
    textColor: _54,
    thickness: _55,
    lineStyle: _56,
    rounded: _57,
    defaultValue: _58,
    placeholder: _59,
    // 기타 noise
    value: _60,
    valueDefault: _61,
    maxLength: _62,
    minLength: _63,
    variant: _64,
    disabled: _65,
    required: _66,
    helperText: _67,
    readonly: _68,
    ...domProps
  } = props as any;
  /* eslint-enable @typescript-eslint/no-unused-vars */

  // 라벨 (컴포넌트 상단)
  const renderLabel = () =>
    (component as any).label &&
    (component as any).style?.labelDisplay !== false && (
      <label
        style={{
          position: "absolute",
          top: "-25px",
          left: "0px",
          fontSize: (component as any).style?.labelFontSize || "14px",
          color: getAdaptiveLabelColor((component as any).style?.labelColor),
          fontWeight: 500,
        }}
      >
        {(component as any).label}
        {(component as any).required && (
          <span style={{ color: "hsl(var(--destructive))" }}>*</span>
        )}
      </label>
    );

  // Horizontal + text: "─── 텍스트 ───"
  if (orientation === "horizontal" && text) {
    return (
      <div
        style={containerStyle}
        className={className}
        onClick={handleClick}
        onDragStart={onDragStart}
        onDragEnd={onDragEnd}
        {...filterDOMProps(domProps)}
      >
        {renderLabel()}
        <div
          style={{
            flex: 1,
            height: 0,
            borderTop: `${thickness} ${lineStyle} ${color}`,
          }}
        />
        <span
          style={{
            padding: "0 12px",
            color: textColor,
            fontSize: "14px",
            whiteSpace: "nowrap",
          }}
        >
          {text}
        </span>
        <div
          style={{
            flex: 1,
            height: 0,
            borderTop: `${thickness} ${lineStyle} ${color}`,
          }}
        />
      </div>
    );
  }

  // Horizontal line
  if (orientation === "horizontal") {
    return (
      <div
        style={containerStyle}
        className={className}
        onClick={handleClick}
        onDragStart={onDragStart}
        onDragEnd={onDragEnd}
        {...filterDOMProps(domProps)}
      >
        {renderLabel()}
        <div
          style={{
            width: "100%",
            height: 0,
            borderTop: `${thickness} ${lineStyle} ${color}`,
            borderRadius: rounded ? "999px" : 0,
          }}
        />
      </div>
    );
  }

  // Vertical line
  return (
    <div
      style={containerStyle}
      className={className}
      onClick={handleClick}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      {...filterDOMProps(domProps)}
    >
      {renderLabel()}
      <div
        style={{
          width: 0,
          height: "100%",
          borderLeft: `${thickness} ${lineStyle} ${color}`,
        }}
      />
    </div>
  );
};

/**
 * 래퍼 — 외부에서 import 하기 편한 표준 이름
 */
export const DividerWrapper: React.FC<DividerComponentProps> = (props) => {
  return <DividerComponent {...props} />;
};
