'use client'

import { TextField } from './TextField.js'
import { RichTextField } from './RichTextField.js'
import { SlugField } from './SlugField.js'
import { SelectField } from './SelectField.js'
import { MediaField } from './MediaField.js'
import { RelationshipField } from './RelationshipField.js'
import { DateField } from './DateField.js'
import { ToggleField } from './ToggleField.js'
import { ArrayField } from './ArrayField.js'
import { BlockBuilderField } from './BlockBuilderField.js'
import { GroupField } from './GroupField.js'
import { NavBuilderField } from './NavBuilderField.js'
import { NumberField } from './NumberField.js'
import { ComponentBlockField } from './ComponentBlockField.js'

export interface FieldDefinition {
  name: string
  type: string
  label: string
  required?: boolean
  maxLength?: number
  helpText?: string
  options?: string[]
  min?: number
  max?: number
  from?: string
  multi?: boolean
  fields?: FieldDefinition[]
  blocks?: any[]
  manifest?: unknown
  allow?: string[]
  defaultComponent?: string
}

export interface FieldRendererProps {
  field: FieldDefinition
  value: any
  onChange: (value: any) => void
}

const FIELD_MAP: Record<string, React.ComponentType<any>> = {
  text: TextField,
  richText: RichTextField,
  slug: SlugField,
  select: SelectField,
  media: MediaField,
  relationship: RelationshipField,
  date: DateField,
  toggle: ToggleField,
  array: ArrayField,
  blocks: BlockBuilderField,
  group: GroupField,
  nav: NavBuilderField,
  number: NumberField,
  componentBlock: ComponentBlockField,
}

export function FieldRenderer({ field, value, onChange }: FieldRendererProps) {
  const Component = FIELD_MAP[field.type]

  if (!Component) {
    return (
      <div className="rounded-md border border-[var(--destructive)] bg-red-50 p-3 text-sm text-[var(--destructive)]">
        Unknown field type: <code>{field.type}</code>
      </div>
    )
  }

  return (
    <Component
      label={field.label}
      value={value}
      onChange={onChange}
      required={field.required}
      maxLength={field.maxLength}
      helpText={field.helpText}
      options={field.options}
      min={field.min}
      max={field.max}
      from={field.from}
      multi={field.multi}
      fields={field.fields}
      blocks={field.blocks}
      name={field.name}
      manifest={field.manifest}
      allow={field.allow}
      defaultComponent={field.defaultComponent}
    />
  )
}
