import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  RefreshControl,
  TextInput,
} from 'react-native';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../navigation/types';
import { Project } from '../types';
import { getAllProjects } from '../lib/db/repositories';
import { Button, ProjectCard, EmptyState } from '../components';
import { colors, spacing, typography, borderRadius } from '../lib/theme';
import { useAuth } from '../contexts/AuthContext';

type NavigationProp = NativeStackNavigationProp<RootStackParamList>;

type SortOption = 'newest' | 'oldest' | 'name';

export const ProjectsScreen: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  const { user } = useAuth();
  const [projects, setProjects] = useState<Project[]>([]);
  const [filteredProjects, setFilteredProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [sortBy, setSortBy] = useState<SortOption>('newest');
  const [searchQuery, setSearchQuery] = useState('');

  const sortProjects = (projectsToSort: Project[]) => {
    const sorted = [...projectsToSort];
    switch (sortBy) {
      case 'newest':
        return sorted.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
      case 'oldest':
        return sorted.sort((a, b) => new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime());
      case 'name':
        return sorted.sort((a, b) => a.title.localeCompare(b.title));
      default:
        return sorted;
    }
  };

  const filterProjects = (projectsToFilter: Project[], query: string) => {
    if (!query.trim()) return projectsToFilter;

    const lowerQuery = query.toLowerCase();
    return projectsToFilter.filter(project =>
      project.title.toLowerCase().includes(lowerQuery) ||
      project.tags.some(tag => tag.toLowerCase().includes(lowerQuery))
    );
  };

  const loadProjects = async () => {
    if (!user) return;

    try {
      const allProjects = await getAllProjects(user.id);
      const sorted = sortProjects(allProjects);
      setProjects(sorted);
      setFilteredProjects(filterProjects(sorted, searchQuery));
    } catch (error) {
      console.error('Failed to load projects:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(
    useCallback(() => {
      loadProjects();
    }, [])
  );

  useEffect(() => {
    if (projects.length > 0) {
      const sorted = sortProjects(projects);
      setProjects(sorted);
      setFilteredProjects(filterProjects(sorted, searchQuery));
    }
  }, [sortBy]);

  useEffect(() => {
    setFilteredProjects(filterProjects(projects, searchQuery));
  }, [searchQuery]);

  const handleRefresh = () => {
    setRefreshing(true);
    loadProjects();
  };

  const handleCreateProject = () => {
    navigation.navigate('ProjectDetail', { projectId: 'new' });
  };

  const handleProjectPress = (projectId: string) => {
    navigation.navigate('ProjectDetail', { projectId });
  };

  const getStepCount = (projectId: string) => {
    // This will be calculated from actual steps
    return 0; // Placeholder
  };

  const renderProject = ({ item }: { item: Project }) => {
    const stepCount = getStepCount(item.id);

    return (
      <ProjectCard
        project={item}
        onPress={handleProjectPress}
        variant="grid"
        showStepCount
        stepCount={stepCount}
      />
    );
  };

  if (loading) {
    return (
      <View style={styles.centerContainer}>
        <Text>Loading projects...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {filteredProjects.length === 0 && searchQuery.length > 0 ? (
        <EmptyState
          icon="🔍"
          title="No matches found"
          description="Try a different search term"
        />
      ) : projects.length === 0 ? (
        <EmptyState
          icon="🏺"
          title="No projects yet"
          description="Start your first piece!"
          actionLabel="New Project"
          onAction={handleCreateProject}
          buttonStyle={styles.sageButton}
        />
      ) : (
        <FlatList
          data={filteredProjects}
          renderItem={renderProject}
          keyExtractor={(item) => item.id}
          numColumns={2}
          columnWrapperStyle={styles.columnWrapper}
          contentContainerStyle={styles.listContent}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
          }
          ListHeaderComponent={
            <View>
              {/* MY PROJECTS Title */}
              <View style={styles.header}>
                <Text style={styles.headerTitle}>My Projects</Text>
              </View>

              {/* Create Project Button */}
              <View style={styles.buttonContainer}>
                <Button
                  title="New Project"
                  onPress={handleCreateProject}
                  size="md"
                  style={styles.sageButton}
                  accessibilityLabel="Create new project"
                />
              </View>

              {/* Search Bar */}
              <View style={styles.searchContainer}>
                <TextInput
                  style={styles.searchInput}
                  placeholder="Search projects or tags..."
                  value={searchQuery}
                  onChangeText={setSearchQuery}
                  placeholderTextColor={colors.textSecondary}
                />
                {searchQuery.length > 0 && (
                  <TouchableOpacity onPress={() => setSearchQuery('')} style={styles.clearButton}>
                    <Text style={styles.clearButtonText}>✕</Text>
                  </TouchableOpacity>
                )}
              </View>

              {/* Sort Buttons */}
              <View style={styles.sortContainer}>
                <Text style={styles.sortLabel}>Sort:</Text>
                <TouchableOpacity
                  style={[styles.sortButton, sortBy === 'newest' && styles.sortButtonActive]}
                  onPress={() => setSortBy('newest')}
                >
                  <Text style={[styles.sortButtonText, sortBy === 'newest' && styles.sortButtonTextActive]}>
                    Newest
                  </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={[styles.sortButton, sortBy === 'oldest' && styles.sortButtonActive]}
                  onPress={() => setSortBy('oldest')}
                >
                  <Text style={[styles.sortButtonText, sortBy === 'oldest' && styles.sortButtonTextActive]}>
                    Oldest
                  </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={[styles.sortButton, sortBy === 'name' && styles.sortButtonActive]}
                  onPress={() => setSortBy('name')}
                >
                  <Text style={[styles.sortButtonText, sortBy === 'name' && styles.sortButtonTextActive]}>
                    Name
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          }
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.backgroundSecondary,
  },
  centerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonContainer: {
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
    paddingBottom: spacing.md,
    backgroundColor: colors.background,
  },
  header: {
    paddingTop: 64,
    paddingBottom: spacing.lg,
    backgroundColor: colors.background,
    borderBottomWidth: 3,
    borderBottomColor: colors.primary,
  },
  headerTitle: {
    fontSize: typography.fontSize.xl,
    fontWeight: typography.fontWeight.bold,
    color: colors.primary,
    letterSpacing: 0.5,
    textTransform: 'uppercase',
    paddingHorizontal: spacing.lg,
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.md,
    paddingBottom: spacing.md,
  },
  searchInput: {
    flex: 1,
    backgroundColor: colors.backgroundSecondary,
    borderRadius: borderRadius.md,
    borderWidth: 2,
    borderColor: colors.border,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    fontSize: typography.fontSize.sm,
    color: colors.text,
    fontWeight: typography.fontWeight.medium,
  },
  clearButton: {
    position: 'absolute',
    right: spacing.lg + spacing.md,
    paddingHorizontal: spacing.sm,
  },
  clearButtonText: {
    fontSize: typography.fontSize.lg,
    color: colors.textSecondary,
    fontWeight: typography.fontWeight.bold,
  },
  sortContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: spacing.lg,
    paddingBottom: spacing.md,
    gap: spacing.sm,
  },
  sortLabel: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.bold,
    color: colors.textSecondary,
    letterSpacing: 0.5,
    textTransform: 'uppercase',
  },
  sortButton: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: borderRadius.full,
    borderWidth: 2,
    borderColor: colors.border,
    backgroundColor: colors.backgroundSecondary,
  },
  sortButtonActive: {
    borderColor: colors.primary,
    backgroundColor: colors.primaryLight,
  },
  sortButtonText: {
    fontSize: typography.fontSize.xs,
    fontWeight: typography.fontWeight.bold,
    color: colors.textSecondary,
    letterSpacing: 0.3,
  },
  sortButtonTextActive: {
    color: colors.text,
  },
  listContent: {
    paddingBottom: 100, // Extra space for floating tab bar
  },
  columnWrapper: {
    gap: spacing.md,
    paddingHorizontal: spacing.lg,
  },
  sageButton: {
    backgroundColor: '#8B9A7C',
    borderColor: '#7A896C',
    // Floating effect
    shadowColor: '#000000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 8,
  },
});

