import React, { useEffect, useState } from 'react';
import { ScrollView, View, Text, Dimensions, SafeAreaView } from 'react-native';
import { getDBConnection } from '@/database/sqlite';
import { LineChart, PieChart } from 'react-native-chart-kit';
import { useIsFocused } from '@react-navigation/native';

export default function AnalyticsScreen() {
  const [totalKm, setTotalKm] = useState(0);
  const [totalKcal, setTotalKcal] = useState(0);
  const [sportDistribution, setSportDistribution] = useState<any[]>([]);
  const isFocused = useIsFocused();

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

  const loadStats = async () => {
    try {
      const db = await getDBConnection();
      const resTotal: any = await db.getFirstAsync('SELECT SUM(distance) as dist, SUM(calories) as kcal FROM workouts');
      setTotalKm(resTotal?.dist || 0);
      setTotalKcal(resTotal?.kcal || 0);

      const distData: any[] = await db.getAllAsync(
        'SELECT type, COUNT(id) as count FROM workouts GROUP BY type'
      );
      const chartColors = ['#10b981', '#4f46e5', '#f59e0b'];
      const formattedPie = distData.map((d, index) => ({
        name: d.type,
        population: d.count,
        color: chartColors[index % chartColors.length],
        legendFontColor: '#94a3b8',
        legendFontSize: 11
      }));
      setSportDistribution(formattedPie);
    } catch (error) {
      console.error("Error loading stats:", error);
    }
  };

  const screenWidth = Dimensions.get('window').width;

  return (
    <SafeAreaView className="flex-1 bg-[#050811]">
      <ScrollView className="p-4" showsVerticalScrollIndicator={false}>
        <Text className="text-lg font-black text-white uppercase tracking-wider mb-4">Biểu Đồ Xu Hướng</Text>

        <View className="flex-row gap-3 mb-6">
          <View className="flex-1 bg-slate-950 border border-slate-900 rounded-2xl p-4">
            <Text className="text-[9px] text-slate-500 font-extrabold uppercase">Tổng quãng đường</Text>
            <Text className="text-2xl font-black text-emerald-400 mt-1">{totalKm.toFixed(1)} <Text className="text-xs">km</Text></Text>
          </View>
          <View className="flex-1 bg-slate-950 border border-slate-900 rounded-2xl p-4">
            <Text className="text-[9px] text-slate-500 font-extrabold uppercase">Năng lượng tiêu hao</Text>
            <Text className="text-2xl font-black text-orange-500 mt-1">{totalKcal} <Text className="text-xs">Kcal</Text></Text>
          </View>
        </View>

        <View className="bg-slate-950 border border-slate-900 rounded-3xl p-4 mb-6">
          <Text className="text-xs font-bold text-white mb-4 uppercase tracking-wider">Tiến trình tích lũy cự ly</Text>
          <LineChart
            data={{
              labels: ['Th 2', 'Th 3', 'Th 4', 'Th 5', 'Th 6', 'Th 7', 'CN'],
              datasets: [{ data: [12, 18, 15, 25, 30, 48, totalKm > 0 ? totalKm : 10] }]
            }}
            width={screenWidth - 40}
            height={180}
            chartConfig={chartConfig}
            bezier
            style={{ borderRadius: 16 }}
          />
        </View>

        <View className="bg-slate-950 border border-slate-900 rounded-3xl p-4 mb-6">
          <Text className="text-xs font-bold text-white mb-3 uppercase tracking-wider">Tỷ lệ hình thức tập thể dục</Text>
          {sportDistribution.length > 0 ? (
            <PieChart
              data={sportDistribution}
              width={screenWidth - 40}
              height={150}
              chartConfig={chartConfig}
              accessor="population"
              backgroundColor="transparent"
              paddingLeft="15"
              absolute
            />
          ) : (
            <Text className="text-xs text-slate-500 text-center py-6">Chưa có dữ liệu phân loại môn thể thao</Text>
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const chartConfig = {
  backgroundGradientFrom: '#050811',
  backgroundGradientTo: '#090d16',
  color: (opacity = 1) => `rgba(16, 185, 129, ${opacity})`,
  labelColor: (opacity = 1) => `rgba(148, 163, 184, ${opacity})`,
  strokeWidth: 3,
  decimalPlaces: 0,
};
