import type { SegmentProps } from '@zag-js/date-input'
import { mergeProps } from '@zag-js/solid'
import { createMemo } from 'solid-js'
import { createSplitProps } from '../../utils/create-split-props.ts'
import { type HTMLProps, type PolymorphicProps, ark } from '../factory.tsx'
import { useDateInputContext } from './use-date-input-context.ts'
import { useDateInputSegmentGroupPropsContext } from './use-date-input-segment-group-props-context.ts'

export interface DateInputSegmentBaseProps extends PolymorphicProps<'span'>, Pick<SegmentProps, 'segment'> {}
export interface DateInputSegmentProps extends HTMLProps<'span'>, DateInputSegmentBaseProps {}

const splitSegmentProps = createSplitProps<Pick<SegmentProps, 'segment'>>()

type IndexedSegment = SegmentProps['segment'] & { index?: number }

export const DateInputSegment = (props: DateInputSegmentProps) => {
  const [segmentProps, localProps] = splitSegmentProps(props, ['segment'])
  const segmentGroupProps = useDateInputSegmentGroupPropsContext()
  const api = useDateInputContext()

  // `type` alone doesn't identify a segment, since multiple segments can share it (e.g. `literal`)
  const currentSegment = createMemo(() => {
    const index = (segmentProps.segment as IndexedSegment).index
    const segments = api().getSegments(segmentGroupProps)
    return (typeof index === 'number' ? segments[index] : undefined) ?? segmentProps.segment
  })

  const mergedProps = mergeProps(
    () => api().getSegmentProps({ segment: currentSegment(), index: segmentGroupProps.index }),
    localProps,
  )
  return <ark.span {...mergedProps}>{currentSegment().text}</ark.span>
}
