'use client'

import { forwardRef, type InputHTMLAttributes, type ReactNode, type TextareaHTMLAttributes } from 'react'
import { cn } from '@/lib/utils'

/**
 * Forge Input — implements DESIGN.md §4.Input
 *
 * Sizes
 *  - sm : 32 (inline edit)
 *  - md : 36 (default — settings)
 *  - lg : 40 (form / dialog)
 */

export type InputSize = 'sm' | 'md' | 'lg'

export interface InputProps
  extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size' | 'prefix'> {
  inputSize?: InputSize
  prefix?: ReactNode
  suffix?: ReactNode
  invalid?: boolean
  /**
   * Suppress browser password-manager autofill. Adds the readOnly-onFocus trick
   * + non-credential `name`. Use for any field that is NOT login.
   */
  suppressAutofill?: boolean
}

const sizeClasses: Record<InputSize, string> = {
  sm: 'h-8 text-[12px]',
  md: 'h-9 text-[13px]',
  lg: 'h-10 text-[13px]',
}

export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
  {
    inputSize = 'md',
    prefix,
    suffix,
    invalid = false,
    suppressAutofill = false,
    className,
    onFocus,
    readOnly,
    name,
    ...rest
  },
  ref,
) {
  const autofillProps = suppressAutofill
    ? {
        autoComplete: rest.type === 'password' ? 'new-password' : 'off',
        // Non-credential name pattern keeps Chrome/Safari from filling.
        name: name ?? `forge-field-${Math.random().toString(36).slice(2, 8)}`,
        'data-1p-ignore': 'true',
        'data-lpignore': 'true',
        'data-form-type': 'other',
      }
    : {}

  const wrapper = (
    <div
      className={cn(
        'flex items-center rounded-control border bg-surface-2 px-3 transition-colors transition-shadow',
        invalid
          ? 'border-accent-danger focus-within:border-accent-danger focus-within:shadow-focus-ring'
          : 'border-hairline focus-within:border-brand-primary focus-within:shadow-focus-ring',
        sizeClasses[inputSize],
        className,
      )}
    >
      {prefix && <span className="mr-2 flex items-center text-ink-subtle">{prefix}</span>}
      <input
        ref={ref}
        readOnly={readOnly}
        onFocus={onFocus}
        name={name}
        {...autofillProps}
        {...rest}
        className={cn(
          'flex-1 bg-transparent outline-none text-ink placeholder:text-ink-tertiary min-w-0',
          'autofill:bg-transparent',
        )}
      />
      {suffix && <span className="ml-2 flex items-center text-ink-subtle">{suffix}</span>}
    </div>
  )

  return wrapper
})

/* --- Field wrapper: label + helper / error --- */

export interface FieldProps {
  label?: ReactNode
  helper?: ReactNode
  error?: ReactNode
  required?: boolean
  htmlFor?: string
  children: ReactNode
}

export function Field({ label, helper, error, required, htmlFor, children }: FieldProps) {
  return (
    <div className="grid gap-1.5">
      {label && (
        <label htmlFor={htmlFor} className="text-[12px] font-medium text-ink-muted">
          {label}
          {required && <span className="ml-1 text-accent-danger">*</span>}
        </label>
      )}
      {children}
      {error ? (
        <p className="text-[11px] text-accent-danger">{error}</p>
      ) : helper ? (
        <p className="text-[11px] text-ink-subtle">{helper}</p>
      ) : null}
    </div>
  )
}

export interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
  invalid?: boolean
}

export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(function Textarea(
  { invalid = false, className, ...rest },
  ref,
) {
  return (
    <textarea
      ref={ref}
      className={cn(
        'w-full rounded-control border bg-surface-2 px-3 py-2 text-[13px] text-ink placeholder:text-ink-tertiary outline-none transition-colors transition-shadow resize-none',
        invalid
          ? 'border-accent-danger focus:border-accent-danger focus:shadow-focus-ring'
          : 'border-hairline focus:border-brand-primary focus:shadow-focus-ring',
        className,
      )}
      {...rest}
    />
  )
})
