'use client'

import { useEffect, useMemo, useState } from 'react'
import type { FieldDefinition } from '@actuate-media/cms-core'
import { cmsApi } from '../../lib/api.js'

const INPUT_CLASS =
  'w-full px-3 py-2 text-sm bg-background border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring'
const LABEL_CLASS = 'text-sm font-medium text-foreground mb-1 block'

interface RelationshipOption {
  id: string
  label: string
}

export interface RelationshipFieldProps {
  definition: FieldDefinition
  value: unknown
  onChange: (value: unknown) => void
  label: string
}

/**
 * Relationship picker for page-builder block fields (e.g. the form block's
 * `formId`). Loads the target collection via the admin API and renders a
 * labelled dropdown. If the collection can't be loaded it degrades to a plain
 * id input so the field is never a dead end.
 */
export function RelationshipField({ definition, value, onChange, label }: RelationshipFieldProps) {
  const relationTo = useMemo(() => {
    if (definition.type !== 'relationship') return ''
    return Array.isArray(definition.relationTo)
      ? (definition.relationTo[0] ?? '')
      : definition.relationTo
  }, [definition])

  const [options, setOptions] = useState<RelationshipOption[]>([])
  const [loading, setLoading] = useState(false)
  const [failed, setFailed] = useState(false)

  useEffect(() => {
    if (!relationTo) return
    let cancelled = false
    setLoading(true)
    setFailed(false)
    cmsApi<Array<Record<string, unknown>>>(`/${relationTo}`)
      .then((res) => {
        if (cancelled) return
        if (Array.isArray(res.data)) {
          setOptions(
            res.data
              .map((item) => ({
                id: String(item.id ?? ''),
                label: String(item.name ?? item.title ?? item.slug ?? item.id ?? 'Untitled'),
              }))
              .filter((option) => option.id),
          )
        } else {
          setFailed(true)
        }
      })
      .catch(() => {
        if (!cancelled) setFailed(true)
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [relationTo])

  const current = (value as string) ?? ''
  const noun = relationTo === 'forms' ? 'a form' : 'an item'

  if (failed) {
    return (
      <div>
        <label className={LABEL_CLASS}>{label}</label>
        <input
          type="text"
          value={current}
          onChange={(e) => onChange(e.target.value || undefined)}
          placeholder={`Enter ${relationTo} id…`}
          className={INPUT_CLASS}
        />
      </div>
    )
  }

  return (
    <div>
      <label className={LABEL_CLASS}>{label}</label>
      <select
        value={current}
        onChange={(e) => onChange(e.target.value || undefined)}
        disabled={loading}
        aria-label={label}
        className={INPUT_CLASS}
      >
        <option value="">{loading ? 'Loading…' : `Select ${noun}…`}</option>
        {options.map((option) => (
          <option key={option.id} value={option.id}>
            {option.label}
          </option>
        ))}
      </select>
      {!loading && options.length === 0 && (
        <p className="text-muted-foreground mt-1 text-xs">No {relationTo} found.</p>
      )}
    </div>
  )
}
