"use client";

import React, { TextareaHTMLAttributes } from "react";
import { PRIMARY_COLOR, type CSSPropertiesWithVars } from "@/lib/common";

interface TextAreaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
  label?: string;            // Optional label
  error?: string;            // Optional validation message
  containerClass?: string;   // Optional container styling
  textareaClass?: string;    // Optional textarea styling
}

export const TextArea: React.FC<TextAreaProps> = ({
  label,
  error,
  containerClass = "",
  textareaClass = "",
  ...props
}) => {
  const baseClasses =
    "w-full rounded-lg border bg-white px-3 py-2 text-sm leading-5 shadow-sm transition-all duration-200 ease-in-out placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-[#428B4D]/15 focus:border-[#428B4D] disabled:bg-gray-100 disabled:text-gray-500 disabled:cursor-not-allowed disabled:hover:border-gray-200 min-h-[7.5rem]";
  const borderClasses = error
    ? "border-red-400 focus:border-red-500 focus:ring-red-400/40"
    : "border-gray-200 hover:border-[#428B4D]/60";
  return (
    <div className={`flex flex-col ${containerClass}`}>
      {label && <label className="mb-1 text-xs font-semibold uppercase tracking-wide text-gray-600">{label}</label>}
      <textarea
        {...props}
        autoComplete="off"
        className={`${baseClasses} ${borderClasses} resize-none ${textareaClass}`}
        style={(!error ? {
          "--focus-border": PRIMARY_COLOR,
          "--focus-ring": `${PRIMARY_COLOR}66`,
          "--hover-border": `${PRIMARY_COLOR}80`,
        } : {}) as CSSPropertiesWithVars}
        onFocus={(e) => {
          if (!error) {
            e.currentTarget.style.borderColor = PRIMARY_COLOR;
            e.currentTarget.style.boxShadow = `0 0 0 1px ${PRIMARY_COLOR}15`;
          }
        }}
        onBlur={(e) => {
          if (!error) {
            e.currentTarget.style.borderColor = "";
            e.currentTarget.style.boxShadow = "";
          }
        }}
        onMouseEnter={(e) => {
          if (!error && document.activeElement !== e.currentTarget && !e.currentTarget.disabled) {
            e.currentTarget.style.borderColor = `${PRIMARY_COLOR}99`;
          }
        }}
        onMouseLeave={(e) => {
          if (!error && document.activeElement !== e.currentTarget) {
            e.currentTarget.style.borderColor = "";
          }
        }}
      />
      {error && <span className="text-red-500 text-sm mt-1">{error}</span>}
    </div>
  );
};
