"use client";

import React from "react";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { WebTypeComponentProps } from "@/lib/registry/types";
import { WidgetComponent, CheckboxTypeConfig } from "@/types/screen";

export const CheckboxWidget: React.FC<WebTypeComponentProps> = ({ component, value, onChange, readonly = false }) => {
  const widget = component as WidgetComponent;
  const { required } = widget;
  const config = widget.webTypeConfig as CheckboxTypeConfig | undefined;

  // 체크박스 값 처리
  const isChecked = value === true || value === "true" || value === "Y" || value === 1;

  const handleChange = (checked: boolean) => {
    // 설정에 따라 값 형식 결정
    const outputValue =
      config?.outputFormat === "YN"
        ? checked
          ? "Y"
          : "N"
        : config?.outputFormat === "10"
          ? checked
            ? 1
            : 0
          : checked;

    onChange?.(outputValue);
  };

  // 체크박스 텍스트
  const checkboxText = config?.text || "체크하세요";

  return (
    <div className="flex h-full w-full items-center space-x-2">
      <Checkbox
        id={`checkbox-${widget.id}`}
        checked={isChecked}
        onCheckedChange={handleChange}
        disabled={readonly}
        required={required}
      />
      <Label
        htmlFor={`checkbox-${widget.id}`}
        className="text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
      >
        {checkboxText}
        {required && <span className="ml-1 text-destructive">*</span>}
      </Label>
    </div>
  );
};

CheckboxWidget.displayName = "CheckboxWidget";


