import React, { useState, useRef, useEffect } from 'react';
import { View, TextInput, Pressable, StyleSheet, Dimensions, Text, Animated, NativeSyntheticEvent, TextInputContentSizeChangeEventData, Platform, ScrollView, ViewStyle, TextStyle } from 'react-native';
import { ArrowUp, FileText, Code, Pen, Search, Maximize2, Minimize2, Plus } from 'lucide-react';
import LoadingTextAnimation from './loading-text-animation';
import { ChatInputProps, CategoryButtonProps } from '../../types';

// Web-specific styles using type assertion
const webInputStyles = Platform.select({
  web: {
    outlineStyle: 'none',
    resize: 'none',
    // Add styles to hide scrollbar on web
    scrollbarWidth: 'none', // Firefox
    msOverflowStyle: 'none', // IE and Edge
  } as const,
  default: {}
});

// Default category buttons
const defaultCategoryButtons: CategoryButtonProps[] = [
  {
    icon: <FileText size={20} color="#E5E7EB" />,
    label: "Summary"
  },
  {
    icon: <Code size={20} color="#E5E7EB" />,
    label: "Code"
  },
  {
    icon: <Pen size={20} color="#E5E7EB" />,
    label: "Design"
  },
  {
    icon: <Search size={20} color="#E5E7EB" />,
    label: "Research"
  }
];

const ChatInput: React.FC<ChatInputProps> = ({
  placeholder = "Ask anything...",
  initialValue = "",
  onSubmit,
  isLoading = false,
  loadingPhrases,
  maxHeight = 120,
  categoryButtons = defaultCategoryButtons,
  containerStyle,
  inputStyle,
  fontFamily = "SpaceMono",
  theme = "dark"
}) => {
  const [inputValue, setInputValue] = useState(initialValue);
  const [isExpanded, setIsExpanded] = useState(false);
  const [textHeight, setTextHeight] = useState(0);
  const [showResizeButton, setShowResizeButton] = useState(false);
  const [isPortrait, setIsPortrait] = useState(false);
  const expandAnim = new Animated.Value(0);
  const inputRef = useRef<TextInput>(null);

  // Define scroll container style with custom max height
  const scrollContainerStyle: ViewStyle = {
    flex: 1,
    minHeight: 56,
    maxHeight,
  };
  
  // Get theme colors
  const colors = getThemeColors(theme);
  
  // Function to handle orientation changes
  const handleOrientationChange = () => {
    const { width, height } = Dimensions.get('window');
    setIsPortrait(height > width);
  };
  
  // Set up orientation listener
  useEffect(() => {
    handleOrientationChange(); // Initial check
    
    // Add listener for dimension changes
    const subscription = Dimensions.addEventListener('change', handleOrientationChange);
    
    // Clean up listener
    return () => {
      // For RN < 0.65, use subscription.remove()
      // For RN >= 0.65, use subscription.remove()
      if (typeof subscription.remove === 'function') {
        subscription.remove();
      } else {
        // @ts-ignore - handle older versions of React Native
        Dimensions.removeEventListener('change', handleOrientationChange);
      }
    };
  }, []);
  
  useEffect(() => {
    if (Platform.OS === 'web') {
      const style = document.createElement('style');
      style.textContent = `
        .no-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .no-scrollbar {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
      `;
      document.head.appendChild(style);

      return () => {
        document.head.removeChild(style);
      };
    }
  }, []);
  
  const handleInputChange = (text: string) => {
    setInputValue(text);
  };

  const handleContentSizeChange = (event: NativeSyntheticEvent<TextInputContentSizeChangeEventData>) => {
    const height = event.nativeEvent.contentSize.height;
    
    setTextHeight(height);
    setShowResizeButton(height > maxHeight);
    
    if (!isExpanded) {
      setTextHeight(Math.min(height, maxHeight));
    }
  };

  const toggleExpand = () => {
    setIsExpanded(!isExpanded);
    Animated.spring(expandAnim, {
      toValue: isExpanded ? 0 : 1,
      useNativeDriver: true,
      tension: 20,
      friction: 7
    }).start();
  };
  
  const animatedContainerStyle = {
    transform: [{
      scale: expandAnim.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 1.1]
      })
    }]
  };
  
  const handleSubmit = () => {
    if (!inputValue.trim() || isLoading) return;
    
    if (onSubmit) {
      onSubmit(inputValue);
    }
    
    setInputValue('');
  };

  return (
    <Animated.View 
      style={[
        styles.container, 
        getContainerStyles(colors),
        animatedContainerStyle, 
        isExpanded && styles.expandedContainer,
        containerStyle
      ]}
    >
      {/* Input area */}
      <View style={styles.inputContainer}>
        <View style={[styles.inputWrapper, isExpanded && styles.expandedInputWrapper]}>
          {isLoading ? (
            <View style={[styles.loadingContainer, { backgroundColor: colors.inputBg }]}>
              <LoadingTextAnimation 
                phrases={loadingPhrases} 
                textStyle={{ color: colors.placeholderColor }}
                fontFamily={fontFamily}
              />
            </View>
          ) : (
            <ScrollView 
              style={scrollContainerStyle}
              showsVerticalScrollIndicator={false}
              showsHorizontalScrollIndicator={false}
              scrollEnabled={true}
              nestedScrollEnabled={true}
            >
              <TextInput
                ref={inputRef}
                placeholder={placeholder}
                placeholderTextColor={colors.placeholderColor}
                style={[
                  styles.input,
                  { 
                    fontFamily,
                    color: colors.textColor,
                    backgroundColor: colors.inputBg
                  },
                  isExpanded ? styles.expandedInput : { height: textHeight },
                  Platform.OS === 'web' && {
                    ...webInputStyles as any,
                    overflow: 'auto',
                  },
                  inputStyle
                ]}
                value={inputValue}
                onChangeText={handleInputChange}
                onContentSizeChange={handleContentSizeChange}
                multiline
                scrollEnabled={true}
              />
            </ScrollView>
          )}
          <View style={styles.buttonGroup}>
            {showResizeButton && !isLoading && (
              <Pressable style={[styles.iconButton, { backgroundColor: colors.buttonBg }]} onPress={toggleExpand}>
                {isExpanded ? 
                  <Minimize2 color={colors.iconColor} size={20} /> :
                  <Maximize2 color={colors.iconColor} size={20} />
                }
              </Pressable>
            )}
            <Pressable style={[styles.sendButton, { backgroundColor: colors.buttonBg }]} onPress={handleSubmit}>
              <View style={styles.sendButtonInner}>
                <ArrowUp color={colors.iconColor} size={24} />
              </View>
            </Pressable>
          </View>
        </View>
      </View>

      {/* Button row */}
      <View style={styles.buttonRowContainer}>
        <View style={styles.buttonRow}>
          <Pressable style={[styles.perfectCircleButton, { backgroundColor: colors.inputBg, borderColor: colors.borderColor }]}>
            <View style={styles.perfectCenterContainer}>
              <Plus size={20} color={colors.iconColor} />
            </View>
          </Pressable>
          {categoryButtons.map((btn, index) => (
            <CategoryButton 
              key={`category-${index}`}
              icon={btn.icon} 
              label={btn.label} 
              isPortrait={isPortrait}
              onPress={btn.onPress}
              style={btn.style}
              iconStyle={btn.iconStyle}
              colors={colors}
              fontFamily={fontFamily}
            />
          ))}
        </View>
      </View>
    </Animated.View>
  );
};

// Category button component
const CategoryButton: React.FC<{
  icon: React.ReactNode;
  label: string;
  isPortrait: boolean;
  style?: ViewStyle;
  iconStyle?: ViewStyle;
  onPress?: () => void;
  colors: ReturnType<typeof getThemeColors>;
  fontFamily?: string;
}> = ({ 
  icon, 
  label, 
  isPortrait,
  style,
  iconStyle,
  onPress,
  colors,
  fontFamily = "SpaceMono"
}) => {
  return (
    <Pressable 
      style={[
        styles.categoryButton,
        { backgroundColor: colors.inputBg, borderColor: colors.borderColor },
        isPortrait && styles.categoryButtonPortrait,
        style
      ]}
      onPress={onPress}
    >
      <View style={[
        styles.iconContainer,
        isPortrait && styles.iconContainerPortrait,
        iconStyle
      ]}>
        {icon}
      </View>
      {!isPortrait && (
        <Text style={[styles.labelText, { fontFamily, color: colors.textColor }]}>{label}</Text>
      )}
    </Pressable>
  );
};

// Theme helper function
function getThemeColors(theme: 'light' | 'dark') {
  if (theme === 'light') {
    return {
      containerBg: '#f9fafb',
      inputBg: '#e5e7eb',
      buttonBg: '#d1d5db',
      textColor: '#111827',
      placeholderColor: '#6b7280',
      iconColor: '#374151',
      borderColor: '#d1d5db'
    };
  }
  
  return {
    containerBg: '#111827',
    inputBg: '#1F2937',
    buttonBg: '#374151',
    textColor: '#E5E7EB',
    placeholderColor: '#9CA3AF',
    iconColor: '#E5E7EB',
    borderColor: '#374151'
  };
}

// Container styles based on theme
function getContainerStyles(colors: ReturnType<typeof getThemeColors>): ViewStyle {
  return {
    backgroundColor: colors.containerBg,
    borderColor: colors.borderColor,
  };
}

const styles = StyleSheet.create({
  container: {
    width: '100%',
    maxWidth: 896,
    borderRadius: 24,
    borderWidth: 1,
    overflow: 'hidden',
    marginBottom: 20,
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 4 },
        shadowOpacity: 0.25,
        shadowRadius: 4,
      },
      android: {
        elevation: 5,
      },
      web: {
        boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
      },
    }),
    zIndex: 1000,
  } as ViewStyle,
  expandedContainer: {
    width: '100%',
    maxWidth: '100%',
    height: 'auto',
    maxHeight: '80%',
  } as ViewStyle,
  inputContainer: {
    padding: 16,
  } as ViewStyle,
  inputWrapper: {
    position: 'relative',
    flexDirection: 'row',
    alignItems: 'flex-start',
  } as ViewStyle,
  expandedInputWrapper: {
    minHeight: 120,
  } as ViewStyle,
  input: {
    flex: 1,
    minHeight: 56,
    maxHeight: Platform.OS === 'web' ? undefined : 120,
    paddingVertical: 16,
    paddingHorizontal: 24,
    paddingRight: 100,
    fontSize: 18,
    borderRadius: 9999,
    textAlignVertical: 'center',
    lineHeight: 24,
    ...(Platform.OS === 'web' ? {
      outline: 'none',
      overflow: 'auto',
    } : {})
  } as TextStyle,
  expandedInput: {
    height: Platform.OS === 'web' ? '60vh' : '60%',
    maxHeight: Platform.OS === 'web' ? '60vh' : '60%',
  } as TextStyle,
  buttonGroup: {
    position: 'absolute',
    right: 8,
    top: '50%',
    transform: [{ translateY: -20 }],
    flexDirection: 'row',
    gap: 8,
    alignItems: 'center',
  } as ViewStyle,
  iconButton: {
    width: 40,
    height: 40,
    borderRadius: 9999,
    justifyContent: 'center',
    alignItems: 'center',
  } as ViewStyle,
  sendButton: {
    width: 40,
    height: 40,
    borderRadius: 9999,
    overflow: 'hidden',
  } as ViewStyle,
  sendButtonInner: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  } as ViewStyle,
  buttonRowContainer: {
    width: '100%',
    paddingHorizontal: 16,
    paddingBottom: 16,
  } as ViewStyle,
  buttonRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
    justifyContent: 'flex-start',
    alignItems: 'center',
  } as ViewStyle,
  categoryButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 9999,
    borderWidth: 1,
  } as ViewStyle,
  categoryButtonPortrait: {
    width: 40,
    height: 40,
    padding: 0,
    justifyContent: 'center',
    alignItems: 'center',
  } as ViewStyle,
  iconContainer: {
    justifyContent: 'center',
    alignItems: 'center',
  } as ViewStyle,
  iconContainerPortrait: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  } as ViewStyle,
  labelText: {
    fontSize: 14,
  } as TextStyle,
  perfectCircleButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    borderWidth: 1,
    overflow: 'hidden',
    position: 'relative',
  } as ViewStyle,
  perfectCenterContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    display: 'flex',
  } as ViewStyle,
  loadingContainer: {
    flex: 1,
    minHeight: 56,
    borderRadius: 9999,
    justifyContent: 'center',
    alignItems: 'flex-start',
    paddingVertical: 16,
  },
});

export default ChatInput;