"use client";

import { useState, FormEvent, KeyboardEvent, useRef, useEffect } from "react";
import { sendMessage } from "@/lib/api";
import { connectSocket } from "@/lib/socket";
import { getAccessToken } from "@/lib/api";
import { Send } from "lucide-react";

interface MessageInputProps {
  channelId: string;
  onSend?: () => void;
}

export function MessageInput({ channelId, onSend }: MessageInputProps) {
  const [content, setContent] = useState("");
  const [isSending, setIsSending] = useState(false);
  const [error, setError] = useState("");
  const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const isTypingRef = useRef(false);

  // Emit typing:stop when component unmounts or channel changes
  useEffect(() => {
    return () => {
      if (isTypingRef.current) {
        const token = getAccessToken();
        if (token) {
          const socket = connectSocket(token);
          socket.emit("typing:stop", { channelId });
        }
      }
      if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
    };
  }, [channelId]);

  const emitTypingStart = () => {
    const token = getAccessToken();
    if (!token) return;
    const socket = connectSocket(token);
    socket.emit("typing:start", { channelId });

    isTypingRef.current = true;

    // Clear previous timeout
    if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
    // Set a new timeout to emit typing:stop after 3s of inactivity
    typingTimeoutRef.current = setTimeout(() => {
      socket.emit("typing:stop", { channelId });
      isTypingRef.current = false;
    }, 3000);
  };

  const handleSubmit = async (e?: FormEvent) => {
    e?.preventDefault();
    const trimmed = content.trim();
    if (!trimmed || isSending) return;

    setIsSending(true);
    setError("");
    try {
      await sendMessage(channelId, trimmed);
      setContent("");
      onSend?.();

      // Emit typing:stop after sending
      if (isTypingRef.current) {
        const token = getAccessToken();
        if (token) {
          const socket = connectSocket(token);
          socket.emit("typing:stop", { channelId });
        }
        isTypingRef.current = false;
        if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
      }
    } catch (err: any) {
      const status = err.response?.status;
      if (status === 401 || status === 403) {
        setError("Your session has expired. Please log in again.");
      } else if (status === 429) {
        setError("You're sending messages too fast. Please slow down.");
      } else if (status >= 500) {
        setError("Server error. Please try again.");
      } else {
        setError("Failed to send message. Please try again.");
      }
    } finally {
      setIsSending(false);
    }
  };

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

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setContent(e.target.value);
    if (e.target.value.trim()) {
      emitTypingStart();
    }
  };

  return (
    <div className="border-t border-gray-200 px-4 py-3">
      {error && (
        <div className="mb-2 p-2 rounded-md bg-red-50 border border-red-200 text-red-700 text-xs">
          {error}
        </div>
      )}
      <form onSubmit={handleSubmit} className="flex items-end gap-2">
        <textarea
          value={content}
          onChange={handleChange}
          onKeyDown={handleKeyDown}
          placeholder={`Send a message`}
          rows={1}
          className="flex-1 resize-none px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm min-h-[40px] max-h-[120px]"
          disabled={isSending}
        />
        <button
          type="submit"
          disabled={isSending || !content.trim()}
          className="p-2 rounded-md bg-slack-purple text-white hover:bg-slack-darkpurple disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
          title="Send message"
        >
          <Send size={20} />
        </button>
      </form>
      <p className="mt-1 text-xs text-gray-400">
        Press Enter to send, Shift+Enter for new line
      </p>
    </div>
  );
}