import type { DynamicFormFieldSchema } from '@/types/dynamic-form-schema-generated';

interface DynamicFormResponseItemProps {
  payload: unknown;
  questionType: string;
  config?: DynamicFormFieldSchema;
}

export function DynamicFormResponseItem({
  payload,
  questionType,
  config,
}: DynamicFormResponseItemProps): string {
  if (!payload || typeof payload !== 'object') {
    return String(payload || '응답 없음');
  }

  const payloadObj = payload as { value?: unknown };
  const value = payloadObj.value;

  // value가 없거나 빈 값인 경우
  if (value === undefined || value === null || value === '') {
    return '응답 없음';
  }

  // options가 있는 필드 타입들 확인
  const getOptions = (
    fieldConfig?: DynamicFormFieldSchema
  ): { label: string; value: string | number }[] | undefined => {
    if (!fieldConfig || typeof fieldConfig !== 'object') return undefined;
    if ('options' in fieldConfig && Array.isArray(fieldConfig.options)) {
      return fieldConfig.options as {
        label: string;
        value: string | number;
      }[];
    }
    return undefined;
  };

  const options = getOptions(config);

  switch (questionType) {
    case 'text':
    case 'textarea':
      return String(value);
    case 'radio':
    case 'select':
    case 'choice':
      if (options) {
        const option = options.find((opt) => opt.value === value);
        return option ? option.label : String(value);
      }
      return String(value);
    case 'checkbox':
    case 'choices': 
      if (Array.isArray(value)) {
        if (options) {
          return value
            .map((val) => {
              const option = options.find((opt) => opt.value === val);
              return option ? option.label : String(val);
            })
            .join(', ');
        }
        return value.join(', ');
      }
      return String(value);
    case 'rating':
      if (options) {
        const option = options.find((opt) => opt.value === value);
        return option ? option.label : String(value);
      }
      return String(value);
    case 'number':
      return String(value);
    case 'yes_no':
      if (value === true || value === 'true' || value === 'yes') {
        return '동의';
      }
      if (value === false || value === 'false' || value === 'no') {
        return '비동의';
      }
      return String(value);
    default:
      return String(value);
  }
}
