"use client";

import { useEffect, useRef, useState } from "react";
import type { QuestionField } from "@/lib/schema-adapter";
import { useI18n } from "@/translations/provider";
import { useQuestionAnswers } from "./question-answer-storage";
import QuestionTitle from "./question-title";

type QuestionTextareaProps = {
  question: QuestionField;
  description?: string;
  disabled?: boolean;
};

export function QuestionTextarea({
  question,
  description,
  disabled,
}: QuestionTextareaProps) {
  const { dictionary: t } = useI18n();
  const { getAnswerValue, setAnswerValue } = useQuestionAnswers();
  const value = getAnswerValue(question);

  const [localValue, setLocalValue] = useState(String(value ?? ""));
  const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    setLocalValue(String(value ?? ""));
  }, [value]);

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const val = e.target.value;
    setLocalValue(val);

    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    debounceTimerRef.current = setTimeout(() => {
      setAnswerValue(question, val);
    }, 300);
  };

  const handleBlur = () => {
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }
    setAnswerValue(question, localValue);
  };

  const stringValue = localValue.trim();
  const isAnswered =
    question.required === false ? true : stringValue.length > 0;

  return (
    <div
      data-question-answered={isAnswered ? "true" : "false"}
      data-question-type="textarea"
      className={[
        "flex w-full flex-col gap-2 transition-opacity duration-200",
        disabled ? "pointer-events-none opacity-30" : "",
      ].join(" ")}
    >
      <QuestionTitle question={question} />
      <textarea
        value={localValue}
        onChange={handleChange}
        onBlur={handleBlur}
        placeholder={question.extras.placeHolder}
        disabled={disabled}
        rows={5}
        className="h-[270px] w-full rounded-[16px] border border-[#D0D5DD] bg-white px-4.5 py-4 text-[15px] font-medium text-[#181818] outline-none transition-all placeholder:text-[#98A2B3] hover:border-[#98A2B3] focus:border-[#6F6F6F] focus:ring-1 focus:ring-[#6F6F6F] disabled:bg-[#F5F2F1] disabled:text-[#7C7472] resize-none"
      />
      {description ? (
        <span className="block group-10 font-semibold text-[#747474]">
          {description}
        </span>
      ) : null}
    </div>
  );
}

export default QuestionTextarea;
