"use client";

import React, { useEffect, useRef, useState } from "react";
import { ComponentRendererProps } from "@/types/component";
import { SearchConfig } from "./types";
import { filterDOMProps } from "@/lib/utils/domPropsFilter";

/**
 * Search — 통합 검색 필터 컴포넌트
 *
 * 흡수 대상:
 *   - v2-table-search-widget (base, 화면 테이블 자동 감지)
 *   - table-search-widget (legacy)
 *   - autocomplete-search-input (legacy, 자동완성은 input 그룹에서 처리)
 *
 * Phase A-4 최소 구현: 단일 input + 검색 버튼. 실제 검색 로직은 DataPort 로
 * 다른 컴포넌트(table 등) 에 searchParams 전달. 복잡한 fields 설정 UI 는
 * Phase F 에서 확장.
 */

export interface SearchComponentProps extends ComponentRendererProps {
  config?: SearchConfig;
}

export const SearchComponent: React.FC<SearchComponentProps> = ({
  component,
  isDesignMode = false,
  isSelected = false,
  onClick,
  onDragStart,
  onDragEnd,
  config,
  className,
  style,
  ...props
}) => {
  // ─── 4경로 머지 ───────────────────────────────────────────────────────
  const fromProps: Partial<SearchConfig> = {};
  const p = props as any;
  if (typeof p.placeholder === "string") fromProps.placeholder = p.placeholder;
  if (typeof p.layout === "string") fromProps.layout = p.layout;
  if (typeof p.dateRangeEnabled === "boolean")
    fromProps.dateRangeEnabled = p.dateRangeEnabled;
  if (typeof p.showResetButton === "boolean")
    fromProps.showResetButton = p.showResetButton;
  if (typeof p.autoSearch === "boolean") fromProps.autoSearch = p.autoSearch;
  if (typeof p.searchButtonText === "string")
    fromProps.searchButtonText = p.searchButtonText;
  if (typeof p.helperText === "string") fromProps.helperText = p.helperText;

  const componentConfig = {
    ...config,
    ...((component as any).config ?? {}),
    ...((component as any).componentConfig ?? {}),
    ...fromProps,
  } as SearchConfig;

  const placeholder = componentConfig.placeholder ?? "검색어를 입력하세요";
  const layout = componentConfig.layout ?? "inline";
  const showResetButton = componentConfig.showResetButton ?? true;
  const autoSearch = componentConfig.autoSearch ?? false;
  const searchButtonText = componentConfig.searchButtonText ?? "검색";
  const helperText = componentConfig.helperText;

  const onSearch =
    typeof (props as any).onSearch === "function"
      ? ((props as any).onSearch as (params: Record<string, any>) => void)
      : undefined;

  const [keyword, setKeyword] = useState("");
  const fillWrapper = isDesignMode === true;

  const emit = (kw: string) => {
    if (isDesignMode || !onSearch) return;
    const trimmed = kw.trim();
    onSearch(trimmed ? { keyword: trimmed } : {});
  };

  const handleSearch = () => emit(keyword);

  const handleReset = () => {
    setKeyword("");
    emit("");
  };

  // autoSearch: 300ms 디바운스
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (!autoSearch || isDesignMode) return;
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => emit(keyword), 300);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyword, autoSearch, isDesignMode]);

  const containerStyle: React.CSSProperties = {
    width: "100%",
    ...(fillWrapper ? { height: "100%" } : { height: "auto" }),
    display: "flex",
    flexDirection: layout === "inline" ? "row" : "column",
    alignItems: layout === "inline" ? "center" : "stretch",
    gap: "6px",
    padding: "6px 8px",
    boxSizing: "border-box",
    background: "transparent",
    alignSelf: fillWrapper ? "stretch" : "center",
    ...(component as any).style,
    ...style,
  };

  if (isDesignMode && isSelected) {
    containerStyle.outline = "2px solid hsl(var(--primary))";
    containerStyle.outlineOffset = "2px";
  }

  const inputStyle: React.CSSProperties = {
    flex: 1,
    minWidth: 0,
    padding: "6px 10px",
    fontSize: "13px",
    border: "1px solid hsl(var(--border))",
    borderRadius: "6px",
    background: "hsl(var(--card))",
    color: "hsl(var(--foreground))",
    outline: "none",
  };

  const btnStyle: React.CSSProperties = {
    padding: "6px 14px",
    fontSize: "13px",
    fontWeight: 600,
    border: "1px solid hsl(var(--primary))",
    background: "hsl(var(--primary))",
    color: "hsl(var(--card))",
    borderRadius: "6px",
    cursor: isDesignMode ? "default" : "pointer",
    whiteSpace: "nowrap",
  };

  const resetBtnStyle: React.CSSProperties = {
    ...btnStyle,
    background: "transparent",
    color: "hsl(var(--muted-foreground))",
    border: "1px solid hsl(var(--border))",
  };

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

  /* 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,
    // ★ SearchConfig 필드 — DOM 에 spread 되면 React warning. 제외.
    placeholder: _51,
    layout: _52,
    dateRangeEnabled: _53,
    showResetButton: _54,
    autoSearch: _55,
    searchButtonText: _56,
    helperText: _57,
    // 기타 noise
    disabled: _58,
    required: _59,
    // Search ↔ Table 연동 props — DOM 에 흘리지 않음
    onSearch: _60,
    searchParams: _61,
    ...domProps
  } = props as any;
  /* eslint-enable @typescript-eslint/no-unused-vars */

  return (
    <div
      style={containerStyle}
      className={className}
      onClick={handleClick}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      {...filterDOMProps(domProps)}
    >
      <input
        type="text"
        value={keyword}
        onChange={(e) => setKeyword(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === "Enter") handleSearch();
        }}
        placeholder={placeholder}
        style={inputStyle}
        disabled={isDesignMode}
      />
      <button
        type="button"
        onClick={handleSearch}
        style={btnStyle}
        disabled={isDesignMode}
      >
        {searchButtonText}
      </button>
      {showResetButton && (
        <button
          type="button"
          onClick={handleReset}
          style={resetBtnStyle}
          disabled={isDesignMode}
        >
          초기화
        </button>
      )}
      {helperText && layout === "stacked" && (
        <span
          style={{
            fontSize: "11px",
            color: "hsl(var(--muted-foreground))",
            marginTop: "2px",
          }}
        >
          {helperText}
        </span>
      )}
    </div>
  );
};

export const SearchWrapper: React.FC<SearchComponentProps> = (props) => {
  return <SearchComponent {...props} />;
};
