"use client";

import type { CheckboxRendererProps } from "./types";

export function CheckboxRenderer({ component, getQueryResult }: CheckboxRendererProps) {
  const checkboxSize = component.checkboxSize || 18;
  const checkboxColor = component.checkboxColor || "#2563eb";
  const checkboxBorderColor = component.checkboxBorderColor || "#6b7280";
  const checkboxLabelPosition = component.checkboxLabelPosition || "right";
  const checkboxLabel = component.checkboxLabel || "";

  const getCheckboxValue = (): boolean => {
    if (component.checkboxFieldName && component.queryId) {
      const queryResult = getQueryResult(component.queryId);
      if (queryResult && queryResult.rows && queryResult.rows.length > 0) {
        const row = queryResult.rows[0];
        const val = row[component.checkboxFieldName];
        if (val === true || val === "true" || val === "Y" || val === 1 || val === "1") return true;
        return false;
      }
      return false;
    }
    return component.checkboxChecked === true;
  };

  const isChecked = getCheckboxValue();

  return (
    <div
      className={`flex h-full w-full items-center gap-2 ${
        checkboxLabelPosition === "left" ? "flex-row-reverse justify-end" : ""
      }`}
    >
      <div
        className="flex items-center justify-center rounded-sm border-2 transition-colors"
        style={{
          width: `${checkboxSize}px`,
          height: `${checkboxSize}px`,
          borderColor: isChecked ? checkboxColor : checkboxBorderColor,
          backgroundColor: isChecked ? checkboxColor : "transparent",
        }}
      >
        {isChecked && (
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="white"
            strokeWidth="3"
            strokeLinecap="round"
            strokeLinejoin="round"
            style={{ width: `${checkboxSize * 0.7}px`, height: `${checkboxSize * 0.7}px` }}
          >
            <polyline points="20 6 9 17 4 12" />
          </svg>
        )}
      </div>
      {checkboxLabel && (
        <span style={{ fontSize: `${component.fontSize || 14}px`, color: component.fontColor || "#374151" }}>
          {checkboxLabel}
        </span>
      )}
    </div>
  );
}
