import { InputHTMLAttributes, ReactNode, SelectHTMLAttributes, TextareaHTMLAttributes } from "react";

type FieldWrapperProps = {
  label: string;
  htmlFor: string;
  error?: string[];
  children: ReactNode;
};

export function FieldWrapper({ label, htmlFor, error, children }: FieldWrapperProps) {
  return (
    <div>
      <label htmlFor={htmlFor} className="mb-1.5 block text-[13px] font-semibold text-text">
        {label}
      </label>
      {children}
      {error?.map((message) => (
        <p key={message} className="mt-1.5 text-[12.5px] text-accent">
          {message}
        </p>
      ))}
    </div>
  );
}

const fieldClass =
  "w-full rounded-xl border border-border bg-surface px-4 py-3 text-[14.5px] text-text outline-none placeholder:text-text-muted/70 focus:border-accent";

type InputProps = InputHTMLAttributes<HTMLInputElement> & {
  label: string;
  error?: string[];
};

export function TextField({ label, error, id, className = "", ...props }: InputProps) {
  const fieldId = id ?? props.name;
  return (
    <FieldWrapper label={label} htmlFor={fieldId!} error={error}>
      <input id={fieldId} className={`${fieldClass} ${className}`} {...props} />
    </FieldWrapper>
  );
}

type TextAreaProps = TextareaHTMLAttributes<HTMLTextAreaElement> & {
  label: string;
  error?: string[];
};

export function TextAreaField({ label, error, id, className = "", ...props }: TextAreaProps) {
  const fieldId = id ?? props.name;
  return (
    <FieldWrapper label={label} htmlFor={fieldId!} error={error}>
      <textarea id={fieldId} rows={3} className={`${fieldClass} resize-none ${className}`} {...props} />
    </FieldWrapper>
  );
}

type SelectProps = SelectHTMLAttributes<HTMLSelectElement> & {
  label: string;
  error?: string[];
  children: ReactNode;
};

export function SelectField({ label, error, id, className = "", children, ...props }: SelectProps) {
  const fieldId = id ?? props.name;
  return (
    <FieldWrapper label={label} htmlFor={fieldId!} error={error}>
      <select id={fieldId} className={`${fieldClass} ${className}`} {...props}>
        {children}
      </select>
    </FieldWrapper>
  );
}
