import type { JSX } from "preact";
import { cn } from "../../utils/cn.ts";

type TextareaSize = "sm" | "md" | "lg";

export interface TextareaProps
  extends Omit<JSX.IntrinsicElements['textarea'], 'size'> {
  label?: string;
  error?: string;
  size?: TextareaSize;
}

export function Textarea(props: TextareaProps): JSX.Element {
  const { class: classProp, label, error, size = "lg", ...rest } = props;

  const sizeClasses = {
    sm: "px-2.5 py-0.5 text-xs",
    md: "px-3 py-1 text-sm",
    lg: "px-4 py-2 text-sm",
  };

  const className = cn(
    "block w-full border border-zinc-200 dark:border-zinc-700 rounded-md bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder:text-zinc-500 dark:placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:border-transparent",
    sizeClasses[size],
    error
      ? "border-red-500 dark:border-red-400 focus:ring-red-500 dark:focus:ring-red-400"
      : "focus:ring-blue-500 dark:focus:ring-blue-400",
    props.disabled && "bg-zinc-50 dark:bg-zinc-800 text-zinc-500 dark:text-zinc-400 cursor-not-allowed",
    classProp,
  );

  return (
    <div>
      {label && (
        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
          {label}
          {props.required && <span className="text-red-500 dark:text-red-400 ml-1">*</span>}
        </label>
      )}
      <textarea class={className} {...rest} />
      {error && <p className="mt-1 text-sm text-red-600 dark:text-red-400">{error}</p>}
    </div>
  );
}
