"use client";
import { useState } from "react";
import { RegisterOptions, UseFormRegister } from "react-hook-form";

function TextareaGroup({
  id,
  label,
  register,
  validation,
  error,
}: {
  label: string;
  id: string;
  register: UseFormRegister<any>;
  validation?: RegisterOptions;
  error?: string;
}) {
  const [isFocused, setIsFocused] = useState(false);
  const [hasValue, setHasValue] = useState(false);

  const { onChange, ...rest } = register(id, validation);

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setHasValue(e.target.value !== "");
    onChange(e);
  };

  return (
    <div>
      <div className="relative w-full my-3">
        <textarea
          className={`border ${
            error
              ? "border-red-500"
              : isFocused
              ? "border-(--primary)"
              : "border-gray-200"
          } p-2 py-3 rounded-lg w-full outline-none resize-vertical min-h-[100px]`}
          id={id}
          {...rest}
          onChange={handleChange}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
        />
        <label
          htmlFor={id}
          className={`absolute left-3 transition-all duration-200 pointer-events-none bg-white px-1 ${
            isFocused || hasValue
              ? "-top-2 text-xs text-gray-600"
              : "top-3 text-base text-gray-400"
          }`}>
          {label}
          <span className="text-red-400">*</span>
        </label>
      </div>
      {error && <p className="text-red-500 text-sm my-3">{error}</p>}
    </div>
  );
}

export default TextareaGroup;
