---
import { cn } from '../lib/cn'
import { baseInputClassNames } from '../lib/formInputs'

import InputWrapper from './InputWrapper.astro'

import type { ComponentProps } from 'astro/types'

type Props = Omit<ComponentProps<typeof InputWrapper>, 'children' | 'inputId'> & {
  accept?: string
  disabled?: boolean
  multiple?: boolean
  removeCheckbox?: {
    name: string
    label: string
  }
}

const { accept, disabled, multiple, removeCheckbox, classNames, ...wrapperProps } = Astro.props

const inputId = Astro.locals.makeId(`input-${wrapperProps.name}`)
const hasError = !!wrapperProps.error && wrapperProps.error.length > 0
---

<InputWrapper
  inputId={inputId}
  classNames={{
    ...classNames,
    description: cn(classNames?.description, '[&:is(:has([data-remove-checkbox]:checked)_~_*)]:hidden'),
  }}
  {...wrapperProps}
>
  {
    !!removeCheckbox && (
      <label
        class={cn(
          'flex cursor-pointer items-center gap-2 py-1 pl-1 text-sm leading-none',
          disabled && 'cursor-not-allowed opacity-50'
        )}
      >
        <input
          transition:persist
          type="checkbox"
          name={removeCheckbox.name}
          data-remove-checkbox
          disabled={disabled}
        />
        {removeCheckbox.label || 'Remove'}
      </label>
    )
  }
  <input
    transition:persist
    type="file"
    id={inputId}
    class={cn(
      baseInputClassNames.input,
      baseInputClassNames.file,
      hasError && baseInputClassNames.error,
      disabled && baseInputClassNames.disabled,
      '[&:is(:has([data-remove-checkbox]:checked)_~_*)]:hidden'
    )}
    required={wrapperProps.required}
    disabled={disabled}
    name={wrapperProps.name}
    accept={accept}
    multiple={multiple}
  />
</InputWrapper>
