import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, FlatList, SafeAreaView } from 'react-native';
import { Calendar } from 'react-native-calendars';
import { getDBConnection } from '@/database/sqlite';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useIsFocused } from '@react-navigation/native';

export default function HistoryScreen() {
  const router = useRouter();
  const isFocused = useIsFocused();
  const [workouts, setWorkouts] = useState<any[]>([]);
  const [markedDates, setMarkedDates] = useState<any>({});
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);

  useEffect(() => {
    if (isFocused) {
      loadCalendarActivities();
    }
  }, [isFocused, selectedDate]);

  const loadCalendarActivities = async () => {
    try {
      const db = await getDBConnection();
      const rows: any[] = await db.getAllAsync('SELECT id, date, type, distance FROM workouts');
      
      const marks: any = {};
      rows.forEach(w => {
        marks[w.date] = {
          marked: true,
          dotColor: w.type === 'CYCLING' ? '#4f46e5' : '#10b981',
          activeOpacity: 0.8
        };
      });
      setMarkedDates(marks);
      fetchWorkoutsByDate(selectedDate);
    } catch (error) {
      console.error("Error loading activities:", error);
    }
  };

  const fetchWorkoutsByDate = async (date: string) => {
    setSelectedDate(date);
    try {
      const db = await getDBConnection();
      const rows: any[] = await db.getAllAsync(
        'SELECT * FROM workouts WHERE date = ?',
        [date]
      );
      setWorkouts(rows);
    } catch (error) {
      console.error("Error loading workouts by date:", error);
    }
  };

  return (
    <SafeAreaView className="flex-1 bg-[#050811]">
      <View className="p-4 flex-1">
        <Text className="text-lg font-black text-white uppercase mb-4 tracking-wider">Nhật Ký Tập Luyện</Text>

        <View className="bg-slate-950 border border-slate-900 rounded-3xl overflow-hidden p-3 mb-4">
          <Calendar
            theme={calendarDarkTheme}
            markedDates={{
              ...markedDates,
              [selectedDate]: {
                ...markedDates[selectedDate],
                selected: true,
                selectedColor: '#10b981'
              }
            }}
            onDayPress={(day) => fetchWorkoutsByDate(day.dateString)}
          />
        </View>

        <FlatList
          data={workouts}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => (
            <TouchableOpacity 
              onPress={() => router.push(`/replay/${item.id}`)}
              className="bg-slate-950 border border-slate-900 rounded-2xl p-4 flex-row items-center justify-between mb-2.5"
            >
              <View className="flex-row items-center gap-3">
                <View className="w-10 h-10 rounded-xl bg-slate-900 flex items-center justify-center">
                  <Ionicons 
                    name={item.type === 'CYCLING' ? 'bicycle' : 'walk'} 
                    size={20} 
                    color={item.type === 'CYCLING' ? '#4f46e5' : '#10b981'} 
                  />
                </View>
                <View>
                  <Text className="text-xs font-black text-white">{item.title}</Text>
                  <Text className="text-[10px] text-slate-500 mt-1">Cự ly: {item.distance.toFixed(2)} km</Text>
                </View>
              </View>
              <Ionicons name="play-circle" size={24} color="#10b981" />
            </TouchableOpacity>
          )}
          ListEmptyComponent={
            <Text className="text-xs text-slate-500 text-center py-8">Không có hoạt động nào trong ngày được chọn.</Text>
          }
        />
      </View>
    </SafeAreaView>
  );
}

const calendarDarkTheme = {
  backgroundColor: '#050811',
  calendarBackground: '#050811',
  textSectionTitleColor: '#64748b',
  selectedDayBackgroundColor: '#10b981',
  selectedDayTextColor: '#090d16',
  todayTextColor: '#10b981',
  dayTextColor: '#cbd5e1',
  textDisabledColor: '#334155',
  dotColor: '#10b981',
  selectedDotColor: '#090d16',
  arrowColor: '#10b981',
  monthTextColor: '#ffffff',
  textMonthFontWeight: 'bold',
  textDayFontSize: 12,
  textMonthFontSize: 14,
} as const;
