import React, { useState, useRef, useEffect, useCallback } from 'react';
import { SendIcon } from '../../assets/icons';
import { useSendMessage, useCurrentConversationId, useCurrentConversationState } from '../../contexts/ChatContext';
import useRenderTracker from '../../hooks/useRenderTracker';

interface InputSectionProps {
  scrollToBottom: (behavior: ScrollBehavior) => void;
}

const InputSection: React.FC<InputSectionProps> = ({ scrollToBottom }) => {
  const sendMessage = useSendMessage();
  const currentConversationId = useCurrentConversationId();
  const currentConversationState = useCurrentConversationState();
  const [inputValue, setInputValue] = useState('');
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const isEnabled = !currentConversationId || currentConversationState?.phase === 'IDLE';

  // Only track if we're at mobile breakpoint (sm:)
  const [isMobile, setIsMobile] = useState(() => 
    typeof window !== 'undefined' ? window.innerWidth < 640 : false
  );

  useRenderTracker('InputSection', {
    currentConversationState,
    inputValue,
    isMobile,
    currentConversationId,
    sendMessage,
    scrollToBottom,
  });

  useEffect(() => {
    const handleResize = () => {
      const mobile = window.innerWidth < 640; // Tailwind's sm: breakpoint
      setIsMobile(mobile);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    }
  }, [inputValue, isMobile]);

  const handleSubmit = useCallback(
    (e?: React.FormEvent) => {
      if (e) e.preventDefault();
      const trimmedValue = inputValue.trim();
      if (trimmedValue && isEnabled) {
        sendMessage(trimmedValue);
        setInputValue('');
        setTimeout(() => {
          scrollToBottom('smooth');
        }, 50);
      }
    },
    [inputValue, isEnabled, sendMessage, scrollToBottom]
  );

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        handleSubmit();
      } else if (e.key === 'Tab') {
        e.preventDefault();
        const start = e.currentTarget.selectionStart;
        const end = e.currentTarget.selectionEnd;
        setInputValue((prevValue) =>
          prevValue.substring(0, start) + '\t' + prevValue.substring(end)
        );
        // Set cursor position after tab
        setTimeout(() => {
          if (textareaRef.current) {
            textareaRef.current.selectionStart = textareaRef.current.selectionEnd = start + 1;
          }
        }, 0);
      }
    },
    [handleSubmit]
  );

  return (
    <form 
      className="w-full mx-auto pb-6 flex-col sm:flex-row" 
      onSubmit={handleSubmit}
    >
      <div className="relative flex items-center rounded-[1.4rem] border bg-gray-200/30 border-gray-200 focus-within:border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:focus-within:border-gray-500 shadow-md">
        <textarea
          ref={textareaRef}
          rows={2}
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyDown={handleKeyDown}
          className="flex-grow resize-none bg-transparent sm:py-[.875rem] py-0 px-4 outline-none focus:ring-0 focus-visible:ring-0 text-[.95rem] max-h-[250px] overflow-y-auto"
          placeholder="Ask anything"
        />
        <button
          className={`btn mx-3 my-3 h-9 w-9 rounded-full bg-black/80 dark:bg-white/70 dark:shadow-lg pr-[.08rem] pt-[.06rem] flex items-center justify-center ${
            inputValue.trim() !== ''
              ? 'enabled:hover:opacity-80'
              : 'disabled:opacity-20'
          }`}
          disabled={inputValue.trim() === '' || !isEnabled}
          type="submit"
        >
          <SendIcon color="currentColor" className="text-white dark:text-black" />
        </button>
      </div>
    </form>
  );
};

export default React.memo(InputSection);
