"use client"

import React, { useCallback, useMemo } from 'react';

import { Input } from '@djangocfg/ui-core/components';
import { WidgetProps } from '@rjsf/utils';

/**
 * Text input widget for JSON Schema Form
 * Handles string fields with optional textarea for multiline
 */
export function TextWidget(props: WidgetProps) {
  const {
    id,
    placeholder,
    required,
    disabled,
    readonly,
    autofocus,
    value,
    onChange,
    onBlur,
    onFocus,
    options,
    schema,
    rawErrors,
  } = props;

  // Memoize widget configuration
  const config = useMemo(() => ({
    isTextarea: options?.widget === 'textarea',
    rows: options?.rows || 3,
    emptyValue: options?.emptyValue,
  }), [options]);

  // Ensure value is always a string
  const safeValue = useMemo(() => {
    if (value === null || value === undefined) return '';
    return String(value);
  }, [value]);

  const hasError = useMemo(() => {
    return rawErrors && rawErrors.length > 0;
  }, [rawErrors]);

  const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const newValue = event.target.value;
    onChange(newValue === '' ? config.emptyValue : newValue);
  }, [onChange, config.emptyValue]);

  const handleBlur = useCallback((event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    onBlur(id, event.target.value);
  }, [id, onBlur]);

  const handleFocus = useCallback((event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    onFocus(id, event.target.value);
  }, [id, onFocus]);

  if (config.isTextarea) {
    return (
      <textarea
        id={id}
        className={`flex min-h-[80px] w-full rounded-md border ${
          hasError ? 'border-destructive' : 'border-input'
        } bg-transparent px-3 py-2 text-base shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm`}
        placeholder={placeholder}
        disabled={disabled || readonly}
        readOnly={readonly}
        autoFocus={autofocus}
        value={safeValue}
        required={required}
        onChange={handleChange}
        onBlur={handleBlur}
        onFocus={handleFocus}
        rows={config.rows}
      />
    );
  }

  return (
    <Input
      id={id}
      type="text"
      placeholder={placeholder}
      disabled={disabled}
      readOnly={readonly}
      autoFocus={autofocus}
      value={safeValue}
      required={required}
      onChange={handleChange}
      onBlur={handleBlur}
      onFocus={handleFocus}
      className={hasError ? 'border-destructive' : ''}
    />
  );
}
