'use client';

import { useState, useRef, useCallback, useEffect } from 'react';
import { Send, Zap } from 'lucide-react';
import { QuickReplyPicker, type QuickReplyTemplate } from './QuickReplyPicker';

interface MessageInputProps {
  onSend: (body: string) => void;
  onTyping?: (isTyping: boolean) => void;
  quickReplies?: QuickReplyTemplate[];
  disabled?: boolean;
  placeholder?: string;
}

export function MessageInput({
  onSend,
  onTyping,
  quickReplies = [],
  disabled = false,
  placeholder = 'Bir mesaj yazın...',
}: MessageInputProps) {
  const [value, setValue] = useState('');
  const [showPicker, setShowPicker] = useState(false);
  const typingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const isTypingRef = useRef(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Yazıyor debounce
  const handleTypingStart = useCallback(() => {
    if (!isTypingRef.current) {
      isTypingRef.current = true;
      onTyping?.(true);
    }
    if (typingTimerRef.current) clearTimeout(typingTimerRef.current);
    typingTimerRef.current = setTimeout(() => {
      isTypingRef.current = false;
      onTyping?.(false);
    }, 2000);
  }, [onTyping]);

  useEffect(() => {
    return () => {
      if (typingTimerRef.current) clearTimeout(typingTimerRef.current);
    };
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setValue(e.target.value);
    if (e.target.value) handleTypingStart();

    // Textarea yüksekliğini içeriğe göre ayarla
    const ta = e.target;
    ta.style.height = 'auto';
    ta.style.height = Math.min(ta.scrollHeight, 120) + 'px';
  };

  const handleSend = () => {
    if (!value.trim() || disabled) return;
    onSend(value);
    setValue('');
    if (typingTimerRef.current) clearTimeout(typingTimerRef.current);
    isTypingRef.current = false;
    onTyping?.(false);
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
    }
  };

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

  const handleQuickReplySelect = (text: string) => {
    setValue(text);
    textareaRef.current?.focus();
  };

  return (
    <div className="relative border-t border-slate-200 bg-white px-4 py-3">
      {showPicker && (
        <QuickReplyPicker
          templates={quickReplies}
          onSelect={handleQuickReplySelect}
          onClose={() => setShowPicker(false)}
        />
      )}

      <div className="flex items-end gap-2">
        {/* Hızlı yanıt butonu */}
        {quickReplies.length > 0 && (
          <button
            type="button"
            onClick={() => setShowPicker((v) => !v)}
            className={`mb-0.5 rounded-lg p-2 transition-colors ${
              showPicker
                ? 'bg-amber-100 text-amber-600'
                : 'text-slate-400 hover:bg-slate-100 hover:text-slate-600'
            }`}
            title="Hızlı yanıtlar"
          >
            <Zap className="h-5 w-5" />
          </button>
        )}

        {/* Metin alanı */}
        <textarea
          ref={textareaRef}
          rows={1}
          value={value}
          onChange={handleChange}
          onKeyDown={handleKeyDown}
          disabled={disabled}
          placeholder={placeholder}
          className="flex-1 resize-none rounded-xl border border-slate-200 bg-slate-50 px-3.5 py-2.5 text-sm text-slate-800 placeholder-slate-400 outline-none transition-colors focus:border-indigo-300 focus:bg-white focus:ring-2 focus:ring-indigo-100 disabled:opacity-60"
          style={{ minHeight: '42px', maxHeight: '120px' }}
        />

        {/* Gönder butonu */}
        <button
          type="button"
          onClick={handleSend}
          disabled={disabled || !value.trim()}
          className="mb-0.5 rounded-xl bg-indigo-600 p-2.5 text-white transition-all hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-40"
        >
          <Send className="h-4 w-4" />
        </button>
      </div>

      <p className="mt-1 text-[11px] text-slate-400">
        <kbd className="font-sans">Enter</kbd> gönder · <kbd className="font-sans">Shift+Enter</kbd> yeni satır
      </p>
    </div>
  );
}
