/**
 * Input Area Component
 * Text input and send button
 * 
 * @since 1.5.0 - Added full appearance preset support
 * @since 1.6.0 - Added new ButtonStyleSettings support for send button
 */

import { useState, useRef, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Send, type LucideIcon } from 'lucide-react';
import { useChatStore } from '@/store/chatStore';
import { resolveValue, resolveTypography, GlobalValues, FieldValue } from '@/utils/resolveAppearance';
import type { PerCornerValue } from '@/types';
import { t } from '@/lib/i18n';
import { HEADER_LUCIDE_ICON_MAP } from '@/utils/headerLucideIconMap';
import { proactiveTimer } from '@/services/ProactiveTimerManager';

function normalizeRadiusString(value: string): string {
  const tokens = value.trim().split(/\s+/).filter(Boolean);
  if (tokens.length === 0) return '12px';
  if (tokens.length === 1) return `${tokens[0]} ${tokens[0]} ${tokens[0]} ${tokens[0]}`;
  if (tokens.length === 2) return `${tokens[0]} ${tokens[1]} ${tokens[0]} ${tokens[1]}`;
  if (tokens.length === 3) return `${tokens[0]} ${tokens[1]} ${tokens[2]} ${tokens[1]}`;
  return `${tokens[0]} ${tokens[1]} ${tokens[2]} ${tokens[3]}`;
}

function radiusToCSS(
  radius: PerCornerValue | FieldValue | string | undefined,
  globalValues: GlobalValues,
  fallback: string
): string {
  if (!radius) return fallback;
  if (typeof radius === 'string') return normalizeRadiusString(radius);
  if (typeof radius === 'object') {
    if ('topLeft' in radius) {
      return `${radius.topLeft} ${radius.topRight} ${radius.bottomRight} ${radius.bottomLeft}`;
    }
    if ('type' in radius) {
      const resolved = resolveValue(radius, globalValues, fallback);
      return normalizeRadiusString(resolved);
    }
  }
  return fallback;
}

export function InputArea() {
  const { sendMessage, isTyping, config, userStartedTyping, userStoppedTyping, setInputFocused, cooldownUntil } = useChatStore();
  const [input, setInput] = useState('');
  const [isHovered, setIsHovered] = useState(false);
  const [cooldownRemaining, setCooldownRemaining] = useState(0);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const wasTypingRef = useRef(false);

  // Week 33: Cooldown countdown timer
  useEffect(() => {
    if (!cooldownUntil || cooldownUntil <= Date.now()) {
      setCooldownRemaining(0);
      return;
    }
    setCooldownRemaining(Math.ceil((cooldownUntil - Date.now()) / 1000));
    const interval = setInterval(() => {
      const remaining = cooldownUntil - Date.now();
      if (remaining <= 0) {
        setCooldownRemaining(0);
        clearInterval(interval);
      } else {
        setCooldownRemaining(Math.ceil(remaining / 1000));
      }
    }, 500);
    return () => clearInterval(interval);
  }, [cooldownUntil]);

  const isCooldownActive = cooldownRemaining > 0;

  // Week 28: visitor input char limit (UI enforcement + counter)
  const inputLimitEnabled = Boolean(config.visitor_input_char_limit_enabled ?? true);
  const inputCharLimit = Math.max(1, Number(config.visitor_input_char_limit ?? 500));
  
  // Get appearance settings
  const globalValues = (config.appearance_preset?.global_values || {}) as GlobalValues;
  const inputSettings = config.element_settings?.inputArea || config.appearance_preset?.element_settings?.inputArea;
  
  // Resolve all input settings
  const inputBackground = resolveValue(inputSettings?.background, globalValues, '#F9FAFB');
  const inputTextColor = resolveValue(inputSettings?.text, globalValues, '#1F2937');
  const inputBorder = resolveValue(inputSettings?.border, globalValues, '#E5E7EB');
  const inputBorderWidth = resolveValue(inputSettings?.borderWidth as FieldValue, globalValues, '1px');
  const inputBorderRadius = resolveValue(inputSettings?.borderRadius, globalValues, '12px');
  const inputPadding = resolveValue(inputSettings?.padding, globalValues, '12px 16px');
  const placeholderText = t(inputSettings?.placeholder || 'Write a message...');
  const placeholderColor = resolveValue(inputSettings?.placeholderColor, globalValues, '#9CA3AF');
  const inputTypography = resolveTypography(inputSettings?.typography as Record<string, FieldValue> | undefined, globalValues, {
    fontFamily: globalValues?.typography?.fontFamily || 'inherit',
    fontSize: '14px',
    fontWeight: '400',
    lineHeight: '1.625',
    letterSpacing: '0px',
    textTransform: 'none',
    fontStyle: 'normal',
    textDecoration: 'none',
    textAlign: 'start',
  });
  const inputTextShadow = resolveValue(
    (inputSettings?.typography as Record<string, FieldValue> | undefined)?.textShadow,
    globalValues,
    'none'
  );
  const counterTextColor = resolveValue(inputSettings?.counterTextColor, globalValues, '#9CA3AF');
  const counterTypography = resolveTypography(
    inputSettings?.counterTextTypography as Record<string, FieldValue> | undefined,
    globalValues,
    {
      fontFamily: globalValues?.typography?.fontFamily || 'inherit',
      fontSize: '10px',
      fontWeight: '400',
      lineHeight: '1',
      letterSpacing: '0px',
      textTransform: 'none',
      fontStyle: 'normal',
      textDecoration: 'none',
      textAlign: 'center',
    }
  );
  const counterTextShadow = resolveValue(
    (inputSettings?.counterTextTypography as Record<string, FieldValue> | undefined)?.textShadow,
    globalValues,
    'none'
  );
  
  // Check for new sendButton style object (ButtonStyleSettings)
  const sendButton = inputSettings?.sendButton;
  const hasNewSendButtonStyle = !!sendButton;
  const isRtl = (window as any).boostbot_config?.is_rtl ?? true;
  
  // New send button style values
  const sendBtnBg = hasNewSendButtonStyle 
    ? resolveValue(sendButton?.backgroundColor as FieldValue, globalValues, config.primary_color || '#3BC2D0')
    : resolveValue(inputSettings?.sendButtonBackground, globalValues, config.primary_color || '#3BC2D0');
  
  // Icon color: prefer icon.color if available (FieldValue), fallback to textColor
  const sendBtnIconColor = hasNewSendButtonStyle
    ? (sendButton?.icon?.color 
        ? resolveValue(sendButton.icon.color as FieldValue, globalValues, '#FFFFFF')
        : resolveValue(sendButton?.textColor as FieldValue, globalValues, '#FFFFFF'))
    : resolveValue(inputSettings?.sendButtonIcon, globalValues, '#FFFFFF');

  const sendBtnIconSizeRaw = hasNewSendButtonStyle ? (sendButton?.icon?.size as unknown as string | undefined) : undefined;
  const sendBtnIconSize = (() => {
    const n = typeof sendBtnIconSizeRaw === 'string' ? parseFloat(sendBtnIconSizeRaw) : NaN;
    return Number.isFinite(n) && n > 0 ? Math.round(n) : 20;
  })();
  
  const sendBtnHoverBg = hasNewSendButtonStyle
    ? resolveValue(sendButton?.hover?.backgroundColor as FieldValue, globalValues, sendBtnBg)
    : sendBtnBg;
  
  // Hover icon color: prefer hover.iconColor if available (FieldValue), fallback to hover.textColor or normal icon color
  const sendBtnHoverIconColor = hasNewSendButtonStyle
    ? (sendButton?.hover?.iconColor
        ? resolveValue(sendButton.hover.iconColor as FieldValue, globalValues, sendBtnIconColor)
        : resolveValue(sendButton?.hover?.textColor as FieldValue, globalValues, sendBtnIconColor))
    : sendBtnIconColor;
  const sendBtnBorderType = sendButton?.borderType || 'none';
  const sendBtnBorderWidth = sendButton?.borderWidth;
  const sendBtnBorderColor = hasNewSendButtonStyle 
    ? resolveValue(sendButton?.borderColor as FieldValue, globalValues, 'transparent')
    : 'transparent';
  const sendBtnHoverBorderColor = hasNewSendButtonStyle
    ? resolveValue(sendButton?.hover?.borderColor as FieldValue, globalValues, sendBtnBorderColor)
    : sendBtnBorderColor;
  const sendBtnBorderRadiusObj = sendButton?.borderRadius;
  const sendBtnBorderRadius = radiusToCSS(sendBtnBorderRadiusObj as PerCornerValue | FieldValue | undefined, globalValues, '12px');
  const sendBtnBoxShadow = hasNewSendButtonStyle
    ? resolveValue(sendButton?.boxShadow as FieldValue, globalValues, 'none')
    : 'none';
  const sendBtnHoverBoxShadow = hasNewSendButtonStyle
    ? resolveValue(sendButton?.hover?.boxShadow as FieldValue, globalValues, sendBtnBoxShadow)
    : sendBtnBoxShadow;
  const sendBtnPaddingObj = sendButton?.padding;
  const sendBtnTransition = sendButton?.transitionDuration || '200ms';
  
  // Dynamic icon selection - read from sendButton.icon.icon or fallback to 'send'
  const sendBtnIconName = (sendButton?.icon as any)?.icon || 'send';
  const SendButtonIcon: LucideIcon = (HEADER_LUCIDE_ICON_MAP[sendBtnIconName] || Send) as LucideIcon;
  const inputDirection = isRtl ? 'rtl' : 'ltr';
  
  // Legacy fallback for send button background
  const sendBtnBackground = sendBtnBg;
  
  // Get container background from chatWindow settings
  const windowSettings = config.element_settings?.chatWindow || config.appearance_preset?.element_settings?.chatWindow;
  const containerBackground = resolveValue(windowSettings?.background, globalValues, '#FFFFFF');
  
  // Auto-resize textarea
  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = 
        Math.min(textareaRef.current.scrollHeight, 100) + 'px';
    }
  }, [input]);
  
  const handleSend = () => {
    const trimmed = input.trim();
    if (!trimmed || isTyping || isCooldownActive) return;
    
    // Clear typing state before sending
    wasTypingRef.current = false;
    userStoppedTyping();
    
    sendMessage(trimmed);
    setInput('');
    
    // Reset textarea height
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
    }
  };
  
  const handleKeyDown = (e: React.KeyboardEvent) => {
    // Send on Enter (without Shift)
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };
  
  const canSend = input.trim().length > 0 && !isTyping && !isCooldownActive;
  
  return (
    <div 
      className="bb-input-area border-t p-3 flex-shrink-0"
      style={{ 
        borderColor: inputBorder,
        borderTopWidth: inputBorderWidth,
        borderTopStyle: 'solid',
        backgroundColor: containerBackground,
      }}
    >
      {/* Custom CSS for placeholder color */}
      <style>
        {`
          .bb-input::placeholder {
            color: ${placeholderColor};
            direction: ${inputDirection};
            text-align: ${isRtl ? 'right' : 'left'};
          }
        `}
      </style>
      
      <div className="flex gap-2 items-end">
        {/* Textarea */}
        <textarea
          ref={textareaRef}
          value={input}
          dir={inputDirection}
          onFocus={() => {
            setInputFocused(true);
            (window as any).__boostbot_inputFocused = true;
            proactiveTimer.onInputFocus();
          }}
          onChange={(e) => {
            setInput(e.target.value);
            (window as any).__boostbot_lastUserTypedAt = Date.now();
            // Notify proactive timer that user is typing
            proactiveTimer.onUserTyping();
            // Typing detection for orchestrator (Phase 2)
            if (e.target.value.length > 0 && !wasTypingRef.current) {
              wasTypingRef.current = true;
              userStartedTyping();
            } else if (e.target.value.length === 0 && wasTypingRef.current) {
              wasTypingRef.current = false;
              userStoppedTyping();
            }
          }}
          onBlur={() => {
            setInputFocused(false);
            (window as any).__boostbot_inputFocused = false;
            proactiveTimer.onInputBlur();
            // User left the input field
            if (wasTypingRef.current) {
              wasTypingRef.current = false;
              userStoppedTyping();
            }
          }}
          onKeyDown={handleKeyDown}
          placeholder={placeholderText}
          className="bb-input flex-1 resize-none outline-none transition-all text-sm leading-relaxed max-h-[100px]"
          style={{
            backgroundColor: inputBackground,
            color: inputTextColor,
            borderRadius: inputBorderRadius,
            padding: inputPadding,
            border: `${inputBorderWidth} solid ${inputBorder}`,
            textShadow: inputTextShadow,
            ...inputTypography,
            textAlign: isRtl ? 'right' : 'left',
          }}
          rows={1}
          disabled={isTyping || isCooldownActive}
          maxLength={inputLimitEnabled ? inputCharLimit : undefined}
          aria-label={t('Write a message')}
        />
        
        {/* Send button - All styles inline to prevent theme CSS override */}
        <motion.button
          className="bb-send-button"
          onClick={handleSend}
          disabled={!canSend}
          onMouseEnter={() => setIsHovered(true)}
          onMouseLeave={() => setIsHovered(false)}
          style={{
            // Size
            width: '40px',
            height: '40px',
            minWidth: '40px',
            minHeight: '40px',
            // Padding from settings or default
            padding: sendBtnPaddingObj 
              ? `${sendBtnPaddingObj.top || '0'} ${sendBtnPaddingObj.right || '0'} ${sendBtnPaddingObj.bottom || '0'} ${sendBtnPaddingObj.left || '0'}`
              : '0',
            // Colors with hover state
            backgroundColor: !canSend ? '#E5E7EB' : (isHovered ? sendBtnHoverBg : sendBtnBackground),
            color: !canSend ? '#9CA3AF' : (isHovered ? sendBtnHoverIconColor : sendBtnIconColor),
            // Border with per-side width support
            borderStyle: sendBtnBorderType !== 'none' ? sendBtnBorderType : 'none',
            borderColor: isHovered ? sendBtnHoverBorderColor : sendBtnBorderColor,
            borderTopWidth: sendBtnBorderWidth?.top || '0',
            borderRightWidth: sendBtnBorderWidth?.right || '0',
            borderBottomWidth: sendBtnBorderWidth?.bottom || '0',
            borderLeftWidth: sendBtnBorderWidth?.left || '0',
            // Border radius
            borderRadius: sendBtnBorderRadius,
            // Shadow
            boxShadow: (isHovered && sendBtnHoverBoxShadow !== 'none') ? sendBtnHoverBoxShadow : (sendBtnBoxShadow !== 'none' ? sendBtnBoxShadow : undefined),
            // Layout
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexShrink: 0,
            // Interaction
            cursor: canSend ? 'pointer' : 'not-allowed',
            outline: 'none',
            // Transition
            transition: `all ${sendBtnTransition} ease`,
          }}
          whileHover={canSend ? { scale: 1.05 } : {}}
          whileTap={canSend ? { scale: 0.95 } : {}}
          aria-label={t('Send message')}
        >
          <SendButtonIcon 
            size={sendBtnIconSize}
            style={{ 
              // Apply color via inline style to prevent theme CSS override
              color: !canSend ? '#9CA3AF' : (isHovered ? sendBtnHoverIconColor : sendBtnIconColor),
              // Only rotate the 'send' icon for RTL, other icons don't need rotation
              transform: (isRtl && sendBtnIconName === 'send') ? 'scaleX(-1)' : undefined,
              flexShrink: 0,
            }} 
          />
        </motion.button>
      </div>
      
      <div className="flex items-center justify-between mt-1">
        {inputLimitEnabled && (
          <p
            style={{
              color: counterTextColor,
              textShadow: counterTextShadow !== 'none' ? counterTextShadow : undefined,
              ...(counterTypography as React.CSSProperties),
            }}
          >
            {input.length}/{inputCharLimit}
          </p>
        )}
        {isCooldownActive && (
          <p
            style={{
              color: '#EF4444',
              fontSize: '11px',
              fontWeight: '500',
              lineHeight: '1',
              ...(inputLimitEnabled ? {} : { marginInlineStart: 'auto' }),
            }}
          >
            {cooldownRemaining} {t('seconds')}
          </p>
        )}
      </div>
    </div>
  );
}
