// src/screens/DashboardScreen.tsx
import React, { useState, useEffect, useCallback } from 'react'; // Added useCallback
import { View, StyleSheet, ScrollView, TouchableOpacity } from 'react-native'; // Added TouchableOpacity
import { Text, TextInput, Button, useTheme, Card, List, Divider, Checkbox, IconButton, ActivityIndicator } from 'react-native-paper'; // Added Checkbox, IconButton, ActivityIndicator
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { format, addDays, startOfDay, isSameDay, parseISO, endOfDay } from 'date-fns'; // Added date-fns imports
import { getCalendarEvents } from '../api/calendar';
import { CalendarEvent } from '../types/calendar';
import { Todo, TodoCreate, TodoUpdate } from '../types/todo'; // Import TODO types
import { getTodos, createTodo, updateTodo, deleteTodo } from '../api/todo'; // Import TODO API functions


// --- TODO Component Implementation ---
const TodoComponent = () => {
  const theme = useTheme();
  const [todos, setTodos] = useState<Todo[]>([]);
  const [newTask, setNewTask] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchTodos = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const fetchedTodos = await getTodos();
      // Add explicit types for sort parameters
      setTodos(fetchedTodos.sort((a: Todo, b: Todo) => a.id - b.id)); 
    } catch (err) {
      console.error("Failed to fetch todos:", err);
      setError("Failed to load TODOs.");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTodos();
  }, [fetchTodos]);

  const handleAddTask = async () => {
    const trimmedTask = newTask.trim();
    if (!trimmedTask) return;

    const newTodoData: TodoCreate = { task: trimmedTask };
    try {
      const createdTodo = await createTodo(newTodoData);
      setTodos(prevTodos => [...prevTodos, createdTodo]);
      setNewTask(''); // Clear input
    } catch (err) {
      console.error("Failed to add todo:", err);
      setError("Failed to add TODO."); // Show error feedback
    }
  };

  const handleToggleComplete = async (todo: Todo) => {
    const updatedTodoData: TodoUpdate = { complete: !todo.complete };
    try {
      const updatedTodo = await updateTodo(todo.id, updatedTodoData);
      setTodos(prevTodos =>
        prevTodos.map(t => (t.id === todo.id ? updatedTodo : t))
      );
    } catch (err) {
      console.error("Failed to update todo:", err);
      setError("Failed to update TODO status.");
    }
  };

  const handleDeleteTask = async (id: number) => {
    try {
      await deleteTodo(id);
      setTodos(prevTodos => prevTodos.filter(t => t.id !== id));
    } catch (err) {
      console.error("Failed to delete todo:", err);
      setError("Failed to delete TODO.");
    }
  };

  const styles = StyleSheet.create({
    card: {
      marginVertical: 8,
      backgroundColor: theme.colors.surface, // Use surface color for card background
    },
    cardTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        paddingLeft: 16,
        paddingTop: 12,
        paddingBottom: 8,
        color: theme.colors.primary,
    },
    inputContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: 16,
      paddingBottom: 12,
    },
    textInput: {
      flex: 1,
      marginRight: 8,
      backgroundColor: theme.colors.background, // Match background
    },
    listItem: {
      paddingVertical: 0, // Reduced padding
      paddingLeft: 8, // Adjust left padding
      backgroundColor: theme.colors.surface, // Ensure item background matches card
      minHeight: 48,
    },
    listCheckboxContainer: {
      justifyContent: 'center',
      height: '100%',
      marginRight: 8,
    },
    listItemContent: {
      marginLeft: -8, // Counteract default List.Item padding if needed
    },
    taskText: {
      fontSize: 15,
      color: theme.colors.onSurface,
    },
    completedTaskText: {
      textDecorationLine: 'line-through',
      color: theme.colors.onSurfaceDisabled,
    },
    deleteButton: {
      marginRight: -8, // Align delete button better
    },
    loadingContainer: {
      padding: 20,
      alignItems: 'center',
      justifyContent: 'center',
    },
    errorText: {
      paddingHorizontal: 16,
      paddingBottom: 12,
      color: theme.colors.error,
    },
    divider: {
        marginHorizontal: 16,
    }
  });

  return (
    <Card style={styles.card} elevation={1}>
      <Card.Content style={{ paddingHorizontal: 0, paddingVertical: 0 }}>
        <Text style={styles.cardTitle}>TODO List</Text>

        {/* Add New Task Input */}
        <View style={styles.inputContainer}>
          <TextInput
            label="New Task"
            value={newTask}
            onChangeText={setNewTask}
            mode="outlined"
            style={styles.textInput}
            dense // Make input smaller
            onSubmitEditing={handleAddTask} // Add task on submit
          />
          <Button mode="contained" onPress={handleAddTask} disabled={!newTask.trim()}>
            Add
          </Button>
        </View>

        {/* Loading Indicator */}
        {loading && (
          <View style={styles.loadingContainer}>
            <ActivityIndicator animating={true} color={theme.colors.primary} />
          </View>
        )}

        {/* Error Message */}
        {error && !loading && <Text style={styles.errorText}>{error}</Text>}

        {/* TODO List */}
        {!loading && !error && todos.length === 0 && (
            <Text style={{ paddingHorizontal: 16, paddingBottom: 12, fontStyle: 'italic', color: theme.colors.onSurfaceDisabled }}>No tasks yet. Add one above!</Text>
        )}
        {!loading && !error && todos.map((todo, index) => (
          <React.Fragment key={todo.id}>
            <List.Item
              style={styles.listItem} // Apply the style with alignItems: 'center'
              title={
                <Text style={[styles.taskText, todo.complete && styles.completedTaskText]}>
                  {todo.task}
                </Text>
              }
              titleNumberOfLines={2} // Allow wrapping
              left={props => (
                <View {...props} style={styles.listCheckboxContainer}>
                  <Checkbox
                    {...props}
                    status={todo.complete ? 'checked' : 'unchecked'}
                    onPress={() => handleToggleComplete(todo)}
                    color={theme.colors.primary}
                  />
                </View>
              )}
              right={props => (
                <IconButton
                  {...props}
                  icon="delete-outline"
                  onPress={() => handleDeleteTask(todo.id)}
                  iconColor={theme.colors.error}
                  style={styles.deleteButton}
                  size={20}
                />
              )}
              contentStyle={styles.listItemContent}
            />
            {index < todos.length - 1 && <Divider style={styles.divider} />}
          </React.Fragment>
        ))}
      </Card.Content>
    </Card>
  );
};
// --- End TODO Component ---

// --- Calendar Preview Component Implementation ---
const CalendarPreview = () => {
  const theme = useTheme();
  const [eventsByDay, setEventsByDay] = useState<{ [key: string]: CalendarEvent[] }>({});
  const today = startOfDay(new Date());
  const days = [today, addDays(today, 1), addDays(today, 2)];

  useEffect(() => {
    const fetchAndProcessEvents = async () => {
      try {
        // Fetch events for the entire 3-day range once
        const endDate = endOfDay(addDays(today, 2)); // Calculate end date to include the whole day
        const allEvents = await getCalendarEvents(today, endDate); // Fetch events until the end of the third day

        // Process events: Group by day
        const groupedEvents: { [key: string]: CalendarEvent[] } = {};
        days.forEach(day => {
          const dayStr = format(day, 'yyyy-MM-dd');
          // Filter events for the current day and sort them
          groupedEvents[dayStr] = allEvents
            .filter(event => isSameDay(parseISO(event.start), day))
            .sort((a, b) => parseISO(a.start).getTime() - parseISO(b.start).getTime());
        });
        setEventsByDay(groupedEvents);
      } catch (error) {
        console.error("Failed to fetch calendar events:", error);
        // Optionally, set an error state here to display to the user
      }
    };
    fetchAndProcessEvents();
  }, []); // Run once on mount

  const formatDateHeader = (date: Date): string => {
    if (isSameDay(date, today)) return `Today, ${format(date, 'MMMM d')}`;
    if (isSameDay(date, addDays(today, 1))) return `Tomorrow, ${format(date, 'MMMM d')}`;
    return format(date, 'EEEE, MMMM d');
  };

  const styles = StyleSheet.create({
    card: {
      marginVertical: 8,
      backgroundColor: theme.colors.background,
    },
    dayHeader: {
      fontSize: 16,
      fontWeight: 'bold',
      paddingLeft: 16,
      paddingTop: 12,
      paddingBottom: 8,
      color: theme.colors.primary,
    },
    listItem: {
      paddingVertical: 4, // Reduce padding slightly
    },
    eventTime: {
      fontSize: 14,
      color: theme.colors.onSurfaceVariant, // Ensure contrast
    },
    eventTitle: {
      fontSize: 15,
      color: theme.colors.onSurface,
    },
    noEventsText: {
      paddingLeft: 16,
      paddingBottom: 12,
      fontStyle: 'italic',
      color: theme.colors.onSurfaceDisabled,
    },
    divider: {
      marginHorizontal: 16,
    }
  });

  return (
    <Card style={styles.card} elevation={1}>
      <Card.Content style={{ paddingHorizontal: 0, paddingVertical: 0 }}>
        {days.map((day, index) => {
          const dayStr = format(day, 'yyyy-MM-dd');
          const dailyEvents = eventsByDay[dayStr] || [];
          return (
            <View key={dayStr}>
              <Text style={styles.dayHeader}>{formatDateHeader(day)}</Text>
              {dailyEvents.length > 0 ? (
                dailyEvents.map((event, eventIndex) => (
                  <React.Fragment key={event.id}>
                    <List.Item
                      title={event.title}
                      titleStyle={styles.eventTitle}
                      description={format(parseISO(event.start), 'p')} // Format time like '1:30 PM'
                      descriptionStyle={styles.eventTime}
                      style={styles.listItem}
                      left={props => <List.Icon {...props} icon="circle-small" />} // Simple indicator
                    />
                    {eventIndex < dailyEvents.length - 1 && <Divider style={styles.divider} />}
                  </React.Fragment>
                ))
              ) : (
                <Text style={styles.noEventsText}>No events scheduled.</Text>
              )}
              {/* Add divider between days, except after the last day */}
              {index < days.length - 1 && <Divider style={{marginTop: 8}} />}
            </View>
          );
        })}
      </Card.Content>
    </Card>
  );
};
// --- End Calendar Preview Component ---

// Define the type for the navigation stack parameters
// Ensure this matches the navigator's configuration
type RootStackParamList = {
  Dashboard: undefined; // No params expected for Dashboard itself
  Chat: { initialQuestion?: string }; // Chat screen expects an optional initialQuestion
  // Add other screens in your stack here
};

// Define the specific navigation prop type for DashboardScreen
type DashboardScreenNavigationProp = StackNavigationProp<RootStackParamList, 'Dashboard'>;

const DashboardScreen = () => {
  const theme = useTheme();
  // Use the specific navigation prop type
  const navigation = useNavigation<DashboardScreenNavigationProp>();
  const [question, setQuestion] = useState('');

  const handleQuestionSubmit = () => {
    const trimmedQuestion = question.trim();
    if (trimmedQuestion) {
      // Navigate to ChatScreen, passing the question as a param
      navigation.navigate('Chat', { initialQuestion: trimmedQuestion });
      // console.log('Navigating to ChatScreen with question:', question); // Keep for debugging if needed
      setQuestion(''); // Clear input after submission
    }
  };

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      // alignItems: 'center', // Keep removed
      justifyContent: 'flex-start',
      padding: 16,
      backgroundColor: theme.colors.background
    },
    title: {
      fontSize: 24,
      fontWeight: 'bold',
      marginBottom: 20,
      color: theme.colors.primary, // Use theme color
      alignSelf: 'center' // Center the title
    },
    inputContainer: {
      marginBottom: 20,
    },
    textInput: {
      marginBottom: 10,
    },
    scrollViewContent: {
        paddingBottom: 20, // Add padding at the bottom of the scroll view
    }
  });

  return (
    // Wrap content in ScrollView to handle potential overflow
    <ScrollView style={{ flex: 1, backgroundColor: theme.colors.background }} contentContainerStyle={styles.scrollViewContent}>
        <View style={styles.container}>
            <Text style={styles.title}>Dashboard</Text>

            {/* AI Question Input */}
            <View style={styles.inputContainer}>
              <TextInput
                label="Ask MAIA anything..."
                value={question}
                onChangeText={setQuestion}
                mode="outlined" // Use outlined style for better visibility
                style={styles.textInput}
                onSubmitEditing={handleQuestionSubmit} // Allow submission via keyboard
              />
              <Button mode="contained" onPress={handleQuestionSubmit}>
                Ask
              </Button>
            </View>

            {/* Calendar Preview */}
            <CalendarPreview />

            {/* TODO Component */}
            <TodoComponent />
        </View>
    </ScrollView>
  );
};

export default DashboardScreen;
