'use client'
import type { CellComponentProps, DefaultCellComponentProps, OptionObject } from 'payload/types'

import { getTranslation } from '@payloadcms/translations'
import { useTranslation } from '@payloadcms/ui/providers/Translation'
import { optionsAreObjects } from 'payload/types'
import React from 'react'

export interface SelectCellProps extends DefaultCellComponentProps<any> {
  options: CellComponentProps['options']
}

export const SelectCell: React.FC<SelectCellProps> = ({ cellData, options }) => {
  const { i18n } = useTranslation()

  const findLabel = (items: string[]) =>
    items
      .map((i) => {
        const found = (options as OptionObject[]).filter((f: OptionObject) => f.value === i)?.[0]
          ?.label
        return getTranslation(found, i18n)
      })
      .join(', ')

  let content = ''
  if (optionsAreObjects(options)) {
    content = Array.isArray(cellData)
      ? findLabel(cellData) // hasMany
      : findLabel([cellData])
  } else {
    content = Array.isArray(cellData)
      ? cellData.join(', ') // hasMany
      : cellData
  }

  return <span>{content}</span>
}
