"use client";

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

export interface CheckboxBasicComponentProps extends ComponentRendererProps {
  config?: CheckboxBasicConfig;
}

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

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

  // 상태 관리
  const [isChecked, setIsChecked] = useState<boolean>(component.value === true || component.value === "true");
  const [checkedValues, setCheckedValues] = useState<string[]>([]);

  // 스타일 계산 (위치는 RealtimePreviewDynamic에서 처리하므로 제외)
  const componentStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    ...component.style,
    ...style,
  };

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

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

  const handleCheckboxChange = (checked: boolean) => {
    setIsChecked(checked);
    if (component.onChange) {
      component.onChange(checked);
    }
    if (isInteractive && onFormDataChange && component.columnName) {
      onFormDataChange(component.columnName, checked);
    }
  };

  const handleGroupChange = (value: string, checked: boolean) => {
    const newValues = checked ? [...checkedValues, value] : checkedValues.filter((v) => v !== value);
    setCheckedValues(newValues);
    if (isInteractive && onFormDataChange && component.columnName) {
      onFormDataChange(component.columnName, newValues.join(","));
    }
  };

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

  // 세부 타입별 렌더링
  const renderCheckboxByWebType = () => {
    // boolean: On/Off 스위치
    if (webType === "boolean") {
      return (
        <label className="flex cursor-pointer items-center gap-3">
          <div className="relative">
            <input
              type="checkbox"
              checked={isChecked}
              onChange={(e) => handleCheckboxChange(e.target.checked)}
              disabled={componentConfig.disabled || isDesignMode}
              className="peer sr-only"
            />
            <div
              className={cn(
                "h-6 w-11 rounded-full transition-colors",
                isChecked ? "bg-blue-600" : "bg-gray-300",
                "peer-focus:ring-2 peer-focus:ring-blue-200",
              )}
            >
              <div
                className={cn(
                  "absolute top-0.5 left-0.5 h-5 w-5 rounded-full bg-white transition-transform",
                  isChecked && "translate-x-5",
                )}
              />
            </div>
          </div>
          <span className="text-sm text-gray-900">{componentConfig.checkboxLabel || component.text || "스위치"}</span>
        </label>
      );
    }

    // checkbox-group: 여러 체크박스
    if (webType === "checkbox-group") {
      const options = componentConfig.options || [
        { value: "option1", label: "옵션 1" },
        { value: "option2", label: "옵션 2" },
        { value: "option3", label: "옵션 3" },
      ];

      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="checkbox"
                value={option.value}
                checked={checkedValues.includes(option.value)}
                onChange={(e) => handleGroupChange(option.value, e.target.checked)}
                disabled={componentConfig.disabled || isDesignMode}
                className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-0 focus:outline-none"
              />
              <span className="text-sm text-gray-900">{option.label}</span>
            </label>
          ))}
        </div>
      );
    }

    // checkbox (기본 체크박스)
    return (
      <label className="flex h-full w-full cursor-pointer items-center gap-3">
        <input
          type="checkbox"
          checked={isChecked}
          disabled={componentConfig.disabled || isDesignMode}
          required={componentConfig.required || false}
          onChange={(e) => handleCheckboxChange(e.target.checked)}
          className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
        />
        <span className="text-sm text-gray-900">{componentConfig.checkboxLabel || component.text || "체크박스"}</span>
      </label>
    );
  };

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

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

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