import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, Pressable, StyleSheet, Platform, ViewStyle, TextStyle, Animated } from 'react-native';
import { ChevronDown, ChevronUp, Plus, Search, Settings } from 'lucide-react';
import { Ionicons } from '@expo/vector-icons';
import { SidebarProps, ProjectItemProps, HistoryItemProps } from '../../types';

// Default projects
const defaultProjects: ProjectItemProps[] = [
  { name: "Frontend Development" },
  { name: "Backend Architecture" }
];

// Default history items
const defaultHistoryItems: HistoryItemProps[] = [
  { name: "Task creation and processing", date: new Date(2024, 2, 15) },
  { name: "API Integration", date: new Date(2024, 2, 14) },
  { name: "Database Schema Design", date: new Date(2024, 2, 14) },
  { name: "User Authentication Flow", date: new Date(2024, 2, 13) },
  { name: "Performance Optimization", date: new Date(2024, 2, 13) }
];

// Custom hook for web-specific styles
const useWebScrollbarStyle = (theme: 'light' | 'dark') => {
  useEffect(() => {
    if (Platform.OS === 'web' && typeof window !== 'undefined') {
      const thumbColor = theme === 'light' ? '#6b7280' : '#FFFFFF';
      const style = document.createElement('style');
      style.textContent = `
        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
          background-color: transparent;
        }
        
        .custom-scrollbar::-webkit-scrollbar-track {
          background-color: transparent;
        }
        
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background-color: ${thumbColor};
          border-radius: 3px;
        }
        
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background-color: ${thumbColor};
        }

        /* For Firefox */
        .custom-scrollbar {
          scrollbar-width: thin;
          scrollbar-color: ${thumbColor} transparent;
        }
      `;
      document.head.appendChild(style);

      return () => {
        document.head.removeChild(style);
      };
    }
  }, [theme]);
};

// Add fixed positioning CSS for web platform
const useFixedPositioningForCollapsed = (isCollapsed: boolean) => {
  useEffect(() => {
    if (Platform.OS === 'web' && typeof window !== 'undefined') {
      const style = document.createElement('style');
      if (isCollapsed) {
        style.textContent = `
          .collapsed-sidebar {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            z-index: 9999 !important;
            margin: 0 !important;
            padding: 0 !important;
          }
        `;
        document.head.appendChild(style);
      }

      return () => {
        if (document.head.contains(style)) {
          document.head.removeChild(style);
        }
      };
    }
  }, [isCollapsed]);
};

const Sidebar: React.FC<SidebarProps> = ({ 
  onCollapsedChange,
  initialCollapsed = false,
  projects = defaultProjects,
  historyItems = defaultHistoryItems,
  subscriptionTitle = "View plans",
  subscriptionText = "Unlimited access, team features,...",
  containerStyle,
  theme = 'dark'
}) => {
  const [isCollapsed, setIsCollapsed] = useState(initialCollapsed);
  const animatedWidth = new Animated.Value(initialCollapsed ? 40 : 256);
  const colors = getThemeColors(theme);
  
  useWebScrollbarStyle(theme);
  useFixedPositioningForCollapsed(isCollapsed);

  const toggleCollapse = () => {
    const newCollapsedState = !isCollapsed;
    setIsCollapsed(newCollapsedState);
    
    if (onCollapsedChange) {
      onCollapsedChange(newCollapsedState);
    }
    
    Animated.timing(animatedWidth, {
      toValue: newCollapsedState ? 40 : 256,
      duration: 300,
      useNativeDriver: false,
    }).start();
  };

  return (
    <Animated.View 
      style={[
        styles.container, 
        { 
          width: animatedWidth, 
          backgroundColor: colors.containerBg,
        },
        isCollapsed && styles.collapsedContainer,
        containerStyle
      ]}
      // react-native doesn't have className
      // className={isCollapsed ? 'collapsed-sidebar' : ''}
    >
      {/* Top icons */}
      <View style={[
        styles.topBar, 
        { borderBottomColor: colors.borderColor },
        isCollapsed && [styles.collapsedTopBar, { backgroundColor: colors.containerBg }]
      ]}>
        <Pressable style={styles.iconButton} onPress={toggleCollapse}>
          <View style={[styles.checkboxIcon, { borderColor: colors.iconColor }]}></View>
        </Pressable>
        {!isCollapsed ? (
          <View style={styles.iconGroup}>
            <Pressable style={styles.iconButton}>
              <Search size={20} color={colors.iconColor} />
            </Pressable>
            <Pressable style={styles.iconButton}>
              <Plus size={20} color={colors.iconColor} />
            </Pressable>
          </View>
        ) : (
          <Pressable style={[styles.iconButton, styles.collapsedPlusButton]}>
            <Plus size={20} color={colors.iconColor} />
          </Pressable>
        )}
      </View>

      {/* Main content - only show when not collapsed */}
      {!isCollapsed && (
        <>
          <ScrollView 
            style={styles.scrollContainer}
            showsVerticalScrollIndicator={false}
            showsHorizontalScrollIndicator={false}
            // className="custom-scrollbar"
          >
            {/* Projects section */}
            <View style={styles.section}>
              <Text style={[styles.sectionTitle, { color: colors.secondaryText }]}>Projects</Text>
              {projects.map((project, index) => (
                <ProjectItem 
                  key={`project-${index}`}
                  name={project.name} 
                  onSelect={project.onSelect}
                  colors={colors}
                />
              ))}
            </View>
            
            {/* History section */}
            <View style={styles.sectionWithMargin}>
              <Text style={[styles.sectionTitle, { color: colors.secondaryText }]}>History</Text>
              {historyItems.map((item, index) => (
                <HistoryItem 
                  key={`history-${index}`}
                  name={item.name} 
                  date={item.date}
                  onSelect={item.onSelect} 
                  colors={colors}
                />
              ))}
            </View>
          </ScrollView>
          
          {/* Bottom subscription link */}
          <View style={[styles.bottomBar, { borderTopColor: colors.borderColor }]}>
            <View style={[styles.subscriptionCard, { backgroundColor: colors.cardBg }]}>
              <View style={styles.subscriptionContent}>
                <View>
                  <Text style={[styles.subscriptionTitle, { color: colors.textColor }]}>{subscriptionTitle}</Text>
                  <Text style={[styles.subscriptionText, { color: colors.secondaryText }]}>{subscriptionText}</Text>
                </View>
                <Settings size={18} color={colors.secondaryText} />
              </View>
            </View>
          </View>
        </>
      )}
    </Animated.View>
  );
};

// Project item component with folder icon
const ProjectItem: React.FC<{
  name: string;
  onSelect?: () => void;
  colors: ReturnType<typeof getThemeColors>;
}> = ({ name, onSelect, colors }) => {
  return (
    <Pressable style={styles.listItem} onPress={onSelect}>
      <Ionicons name="folder-outline" size={20} color={colors.folderIconColor} />
      <Text style={[styles.listItemText, { color: colors.textColor }]}>{name}</Text>
    </Pressable>
  );
};

// History item component with date
const HistoryItem: React.FC<{
  name: string;
  date: Date;
  onSelect?: () => void;
  colors: ReturnType<typeof getThemeColors>;
}> = ({ name, date, onSelect, colors }) => {
  const formattedDate = date.toLocaleDateString('en-US', {
    month: 'numeric',
    day: 'numeric',
    year: '2-digit'
  });
  
  return (
    <Pressable style={styles.listItem} onPress={onSelect}>
      <Text style={[styles.dateText, { color: colors.secondaryText }]}>{formattedDate}</Text>
      <Text style={[styles.listItemText, { color: colors.textColor }]}>{name}</Text>
    </Pressable>
  );
};

// Theme helper function
function getThemeColors(theme: 'light' | 'dark') {
  if (theme === 'light') {
    return {
      containerBg: '#f9fafb',
      cardBg: '#e5e7eb',
      textColor: '#111827',
      secondaryText: '#6b7280',
      borderColor: '#e5e7eb',
      iconColor: '#6b7280',
      folderIconColor: '#6b7280'
    };
  }
  
  return {
    containerBg: '#111827',
    cardBg: '#1f2937',
    textColor: '#f9fafb',
    secondaryText: '#9ca3af',
    borderColor: '#1f2937',
    iconColor: '#d1d5db',
    folderIconColor: '#4b5563'
  };
}

const styles = StyleSheet.create({
  container: {
    height: '100%',
    flexDirection: 'column',
  } as ViewStyle,
  collapsedContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    height: 'auto',
    zIndex: 10000,
    backgroundColor: 'transparent',
    padding: 0,
    margin: 0,
    ...(Platform.OS === 'web' ? {
      position: 'fixed',
    } : {}),
  } as ViewStyle,
  topBar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 12,
    borderBottomWidth: 1,
  } as ViewStyle,
  collapsedTopBar: {
    flexDirection: 'column',
    alignItems: 'flex-start',
    justifyContent: 'flex-start',
    borderBottomWidth: 0,
    borderRadius: 4,
    padding: 0,
    margin: 0,
  } as ViewStyle,
  iconButton: {
    width: 32,
    height: 32,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 4,
  } as ViewStyle,
  collapsedPlusButton: {
    marginTop: 8,
  } as ViewStyle,
  checkboxIcon: {
    width: 20,
    height: 20,
    borderWidth: 2,
    borderRadius: 4,
  } as ViewStyle,
  iconGroup: {
    flexDirection: 'row',
    gap: 12,
  } as ViewStyle,
  scrollContainer: {
    flex: 1,
  } as ViewStyle,
  section: {
    paddingVertical: 8,
  } as ViewStyle,
  sectionWithMargin: {
    marginTop: 16,
  } as ViewStyle,
  sectionTitle: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    fontSize: 12,
    fontWeight: '500',
  } as TextStyle,
  dateText: {
    fontSize: 11,
    width: 45,
    marginRight: 8,
  } as TextStyle,
  listItem: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    flexDirection: 'row',
    alignItems: 'center',
  } as ViewStyle,
  listItemText: {
    marginLeft: 12,
    fontSize: 14,
  } as TextStyle,
  bottomBar: {
    padding: 12,
    borderTopWidth: 1,
  } as ViewStyle,
  subscriptionCard: {
    borderRadius: 8,
    padding: 12,
  } as ViewStyle,
  subscriptionContent: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  } as ViewStyle,
  subscriptionTitle: {
    fontSize: 14,
    fontWeight: '500',
  } as TextStyle,
  subscriptionText: {
    fontSize: 12,
  } as TextStyle,
  collapsedIconGroup: {
    gap: 0,
  } as ViewStyle,
});

export default Sidebar;