"use client";

import React, { useState } from "react";
import { ComponentRendererProps } from "@/types/component";
import { RadioBasicConfig } from "./types";
import { cn } from "@/lib/registry/components/common/inputStyles";
import { filterDOMProps } from "@/lib/utils/domPropsFilter";

export interface RadioBasicComponentProps extends ComponentRendererProps {
  config?: RadioBasicConfig;
}

/**
 * RadioBasic 컴포넌트
 * radio-basic 컴포넌트입니다
 */
export const RadioBasicComponent: React.FC<RadioBasicComponentProps> = ({
  component,
  isDesignMode = false,
  isSelected = false,
  isInteractive = false,
  onClick,
  onDragStart,
  onDragEnd,
  config,
  className,
  style,
  formData,
  onFormDataChange,
  ...props
}) => {
  // 컴포넌트 설정
  const componentConfig = {
    ...config,
    ...component.config,
  } as RadioBasicConfig;

  // webType에 따른 세부 타입 결정 (TextInputComponent와 동일한 방식)
  const webType = component.componentConfig?.webType || "radio";

  // 상태 관리
  const [selectedValue, setSelectedValue] = useState<string>(component.value || "");

  // 스타일 계산 (위치는 RealtimePreviewDynamic에서 처리하므로 제외)
  const componentStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    ...component.style,
    ...style,
    // width는 항상 100%로 고정 (부모 컨테이너가 gridColumns로 크기 제어)
    width: "100%",
  };

  // 디자인 모드 스타일
  if (isDesignMode) {
    componentStyle.border = "1px dashed #cbd5e1";
    componentStyle.borderColor = isSelected ? "#3b82f6" : "#cbd5e1";
  }

  // 이벤트 핸들러
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onClick?.();
  };

  const handleRadioChange = (value: string) => {
    setSelectedValue(value);
    if (component.onChange) {
      component.onChange(value);
    }
    if (isInteractive && onFormDataChange && component.columnName) {
      onFormDataChange(component.columnName, value);
    }
  };

  // DOM 안전한 props만 필터링
  const safeDomProps = filterDOMProps(props);

  // 세부 타입별 렌더링
  const renderRadioByWebType = () => {
    const options = componentConfig.options || [
      { value: "option1", label: "옵션 1" },
      { value: "option2", label: "옵션 2" },
    ];

    // radio-horizontal: 가로 배치
    if (webType === "radio-horizontal") {
      return (
        <div className="flex flex-row gap-4">
          {options.map((option: any, index: number) => (
            <label key={index} className="flex cursor-pointer items-center gap-2">
              <input
                type="radio"
                name={component.id || "radio-group"}
                value={option.value}
                checked={selectedValue === option.value}
                onChange={() => handleRadioChange(option.value)}
                disabled={componentConfig.disabled || isDesignMode}
                className="h-4 w-4 border-input text-primary focus:ring-0 focus:outline-none"
              />
              <span className="text-sm text-foreground">{option.label}</span>
            </label>
          ))}
        </div>
      );
    }

    // radio-vertical: 세로 배치
    if (webType === "radio-vertical") {
      return (
        <div className="flex flex-col gap-2">
          {options.map((option: any, index: number) => (
            <label key={index} className="flex cursor-pointer items-center gap-2">
              <input
                type="radio"
                name={component.id || "radio-group"}
                value={option.value}
                checked={selectedValue === option.value}
                onChange={() => handleRadioChange(option.value)}
                disabled={componentConfig.disabled || isDesignMode}
                className="h-4 w-4 border-input text-primary focus:ring-0 focus:outline-none"
              />
              <span className="text-sm text-foreground">{option.label}</span>
            </label>
          ))}
        </div>
      );
    }

    // radio (기본 라디오 - direction 설정 따름)
    return (
      <div className={cn("flex gap-3", componentConfig.direction === "horizontal" ? "flex-row" : "flex-col")}>
        {options.map((option: any, index: number) => (
          <label key={index} className="flex cursor-pointer items-center gap-2">
            <input
              type="radio"
              name={component.id || "radio-group"}
              value={option.value}
              checked={selectedValue === option.value}
              onChange={() => handleRadioChange(option.value)}
              disabled={componentConfig.disabled || isDesignMode}
              required={componentConfig.required || false}
              className="border-input text-primary h-4 w-4 focus:ring-0"
            />
            <span className="text-sm">{option.label}</span>
          </label>
        ))}
      </div>
    );
  };

  return (
    <div style={componentStyle} className={className} {...safeDomProps}>
      {/* 라벨 렌더링 */}
      {component.label && component.style?.labelDisplay !== false && (
        <label className="absolute -top-6 left-0 text-sm font-medium text-slate-600">
          {component.label}
          {component.required && <span className="text-destructive">*</span>}
        </label>
      )}

      {/* 세부 타입별 UI 렌더링 */}
      {renderRadioByWebType()}
    </div>
  );
};

/**
 * RadioBasic 래퍼 컴포넌트
 * 추가적인 로직이나 상태 관리가 필요한 경우 사용
 */
export const RadioBasicWrapper: React.FC<RadioBasicComponentProps> = (props) => {
  return <RadioBasicComponent {...props} />;
};
