import { cn } from "@/lib/utils";
import { useId } from "react";
import {
  type FieldErrors,
  type FieldValues,
  type Path,
  type UseFormRegister,
  type UseFormRegisterReturn,
} from "react-hook-form";

type PropsType<T extends FieldValues> = {
  name: Path<T>;
  label: string;
  placeholder: string;
  required?: boolean;
  disabled?: boolean;
  active?: boolean;
  className?: string;
  icon?: React.ReactNode;
  defaultValue?: string;
  handleChange?: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
  register?: UseFormRegister<T>;
  errors?: FieldErrors<T>;
} & Partial<UseFormRegisterReturn>;

export function TextAreaGroup<T extends FieldValues>({
  name,
  label,
  placeholder,
  required,
  disabled,
  active,
  className,
  icon,
  defaultValue,
  handleChange,
  register,
  errors,
  onChange,
  onBlur,
  ref,
  ...props
}: PropsType<T>) {
  const id = useId();

  const error = errors && errors[name];

  return (
    <div className={cn(className)}>
      <label
        htmlFor={id}
        className="mb-3 block text-body-sm font-medium text-dark dark:text-white"
      >
        {label}
        {required && <span className="text-red ml-1 select-none">*</span>}
      </label>

      <div className="relative mt-3 [&_svg]:pointer-events-none [&_svg]:absolute [&_svg]:left-5.5 [&_svg]:top-5.5">
        <textarea
          id={id}
          name={name}
          ref={ref}
          rows={6}
          placeholder={placeholder}
          defaultValue={defaultValue}
          onChange={(e) => {
            onChange?.(e);
            handleChange?.(e);
          }}
          onBlur={onBlur}
          className={cn(
            "w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5.5 py-3 text-dark outline-none transition focus:border-primary disabled:cursor-default disabled:bg-gray-2 data-[active=true]:border-primary dark:border-dark-3 dark:bg-dark-2 dark:text-white dark:focus:border-primary dark:disabled:bg-dark dark:data-[active=true]:border-primary",
            error && "border-red focus:border-red dark:border-red",
            icon && "py-5 pl-13 pr-5",
          )}
          required={required}
          disabled={disabled}
          data-active={active}
        />

        {icon}
      </div>

      {error && (
        <p className="text-red mt-1.5 text-sm">{error.message as string}</p>
      )}
    </div>
  );
}
