"use client";

import { useState, useRef, useCallback, KeyboardEvent } from "react";
import { SendHorizontal, Plus, Smile } from "lucide-react";

interface ChatInputProps {
  onSend: (message: string) => void;
  disabled?: boolean;
  channelName: string;
}

export function ChatInput({ onSend, disabled, channelName }: ChatInputProps) {
  const [value, setValue] = useState("");
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const handleSend = useCallback(() => {
    const trimmed = value.trim();
    if (!trimmed || disabled) return;
    onSend(trimmed);
    setValue("");
    // Reset textarea height
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
    }
  }, [value, disabled, onSend]);

  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleInput = () => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = "auto";
      const newHeight = Math.min(textarea.scrollHeight, 200);
      textarea.style.height = `${newHeight}px`;
    }
  };

  return (
    <div className="px-4 pb-6 pt-1 shrink-0">
      <div
        className="flex items-end gap-2 rounded-lg px-4 py-2"
        style={{ backgroundColor: "#40444b" }}
      >
        {/* Attachment button */}
        <button
          className="p-1 rounded-full hover:brightness-125 transition-colors shrink-0 mb-0.5"
          style={{ color: "#96989d" }}
        >
          <Plus className="w-5 h-5" />
        </button>

        {/* Input */}
        <textarea
          ref={textareaRef}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={handleKeyDown}
          onInput={handleInput}
          placeholder={`Message #${channelName}`}
          disabled={disabled}
          rows={1}
          className="flex-1 bg-transparent border-none outline-none resize-none text-[15px] leading-[22px] max-h-[200px] placeholder:opacity-50"
          style={{
            color: "#dcddde",
          }}
        />

        {/* Emoji button */}
        <button
          className="p-1 rounded-full hover:brightness-125 transition-colors shrink-0 mb-0.5"
          style={{ color: "#96989d" }}
        >
          <Smile className="w-5 h-5" />
        </button>

        {/* Send button */}
        <button
          onClick={handleSend}
          disabled={!value.trim() || disabled}
          className="p-1.5 rounded-full transition-all duration-150 shrink-0 mb-0.5"
          style={{
            backgroundColor:
              value.trim() && !disabled ? "#ff6d5a" : "transparent",
            color: value.trim() && !disabled ? "#ffffff" : "#72767d",
            cursor: value.trim() && !disabled ? "pointer" : "default",
          }}
        >
          <SendHorizontal className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}
