/**
 * TableCellRenderer
 * 테이블 셀 = DynamicFieldRenderer를 테이블 셀용 축소 모드로 래핑
 *
 * column config → ItemFieldResponse 호환 객체로 변환 → DynamicFieldRenderer 호출
 */

'use client';

import { DynamicFieldRenderer } from '../fields/DynamicFieldRenderer';
import type { DynamicFieldValue } from '../types';
import type { TableColumnConfig } from '../types';
import type { ItemFieldResponse } from '@/types/item-master-api';

interface TableCellRendererProps {
  column: TableColumnConfig;
  value: DynamicFieldValue;
  onChange: (value: DynamicFieldValue) => void;
  disabled?: boolean;
  rowIndex: number;
}

/**
 * column config를 ItemFieldResponse 호환 객체로 변환
 */
function columnToFieldResponse(column: TableColumnConfig, rowIndex: number): ItemFieldResponse {
  return {
    id: 0,
    tenant_id: 0,
    group_id: null,
    section_id: null,
    field_name: column.label,
    field_key: `table_${column.key}_${rowIndex}`,
    field_type: (column.fieldType || 'textbox') as ItemFieldResponse['field_type'],
    order_no: 0,
    is_required: column.isRequired ?? false,
    placeholder: null,
    default_value: null,
    display_condition: null,
    validation_rules: null,
    options: column.options || null,
    properties: (column.properties as Record<string, any>) || null,
    category: null,
    description: null,
    is_common: false,
    is_locked: false,
    locked_by: null,
    locked_at: null,
    created_by: null,
    updated_by: null,
    created_at: '',
    updated_at: '',
  };
}

export function TableCellRenderer({
  column,
  value,
  onChange,
  disabled,
  rowIndex,
}: TableCellRendererProps) {
  const fieldLike = columnToFieldResponse(column, rowIndex);

  // 읽기 전용 컬럼
  if (column.isReadonly) {
    return (
      <span className="text-sm px-2 py-1 block truncate">
        {value !== null && value !== undefined ? String(value) : '-'}
      </span>
    );
  }

  return (
    <div className="[&_label]:hidden [&_p]:hidden">
      <DynamicFieldRenderer
        field={fieldLike}
        value={value}
        onChange={onChange}
        disabled={disabled}
      />
    </div>
  );
}
