import React from 'react';
import { View, Text, ScrollView, TouchableOpacity, Linking, Alert } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Download, Clock, Calendar, Layers } from 'lucide-react-native';
import { useQuery } from '@tanstack/react-query';
import { useFonts, Inter_400Regular, Inter_600SemiBold } from '@expo-google-fonts/inter';

export default function HistoryScreen() {
  const insets = useSafeAreaInsets();
  const [fontsLoaded, fontError] = useFonts({ Inter_400Regular, Inter_600SemiBold });

  const { data: logs = [], isLoading } = useQuery({
    queryKey: ['logs'],
    queryFn: async () => {
      const res = await fetch(`${process.env.EXPO_PUBLIC_BASE_URL}/api/logs`);
      if (!res.ok) throw new Error('Failed to fetch logs');
      return res.json();
    },
  });

  const handleExport = async () => {
    const exportUrl = `${process.env.EXPO_PUBLIC_BASE_URL}/api/export`;
    const supported = await Linking.canOpenURL(exportUrl);
    if (supported) {
      await Linking.openURL(exportUrl);
    } else {
      Alert.alert('Fout', 'Kan de export-URL niet openen');
    }
  };

  const formatDuration = (seconds: number) => {
    const hrs = Math.floor(seconds / 3600);
    const mins = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    if (hrs > 0) return `${hrs}h ${mins}m`;
    if (mins > 0) return `${mins}m ${secs}s`;
    return `${secs}s`;
  };

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
  };

  const formatTime = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
  };

  if (!fontsLoaded && !fontError) return null;

  return (
    <View style={{ flex: 1, backgroundColor: '#ffffff', paddingTop: insets.top }}>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingHorizontal: 24,
          paddingVertical: 16,
          borderBottomWidth: 1,
          borderBottomColor: '#E5E7EB',
        }}
      >
        <Text
          style={{
            fontSize: 24,
            fontWeight: '600',
            color: '#111827',
            fontFamily: 'Inter_600SemiBold',
          }}
        >
          Geschiedenis
        </Text>
        <TouchableOpacity
          onPress={handleExport}
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: '#EFF6FF',
            paddingHorizontal: 16,
            paddingVertical: 8,
            borderRadius: 999,
            gap: 6,
          }}
        >
          <Download color="#2563EB" size={16} />
          <Text
            style={{
              color: '#2563EB',
              fontWeight: '500',
              fontSize: 13,
              fontFamily: 'Inter_600SemiBold',
            }}
          >
            Exporteer CSV
          </Text>
        </TouchableOpacity>
      </View>

      <ScrollView contentContainerStyle={{ padding: 20 }}>
        {logs.length === 0 && !isLoading ? (
          <View style={{ alignItems: 'center', marginTop: 100 }}>
            <Text style={{ color: '#6B7280', fontSize: 16, fontFamily: 'Inter_400Regular' }}>
              Nog geen opgeslagen sessies.
            </Text>
          </View>
        ) : (
          logs.map((log: any) => (
            <View
              key={log.id}
              style={{
                backgroundColor: '#ffffff',
                borderRadius: 12,
                borderWidth: 1,
                borderColor: '#E5E7EB',
                padding: 16,
                marginBottom: 12,
              }}
            >
              <View
                style={{
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                  alignItems: 'flex-start',
                }}
              >
                <View>
                  <Text
                    style={{
                      fontSize: 16,
                      fontWeight: '600',
                      color: '#111827',
                      marginBottom: 4,
                      fontFamily: 'Inter_600SemiBold',
                    }}
                  >
                    {log.task_name}
                  </Text>
                  <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>
                    <Calendar color="#6B7280" size={12} />
                    <Text
                      style={{ fontSize: 12, color: '#6B7280', fontFamily: 'Inter_400Regular' }}
                    >
                      {formatDate(log.start_time)} • {formatTime(log.start_time)}
                    </Text>
                  </View>
                </View>
                <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
                  {log.insole_type && (
                    <View
                      style={{
                        backgroundColor: '#F3F4F6',
                        borderWidth: 1,
                        borderColor: '#E5E7EB',
                        borderRadius: 999,
                        paddingHorizontal: 10,
                        paddingVertical: 4,
                      }}
                    >
                      <Text
                        style={{
                          fontSize: 13,
                          fontWeight: '600',
                          color: '#374151',
                          fontFamily: 'Inter_600SemiBold',
                        }}
                      >
                        {log.insole_type}
                      </Text>
                    </View>
                  )}
                  {log.pair_count != null && (
                    <View
                      style={{
                        backgroundColor: '#EFF6FF',
                        borderWidth: 1,
                        borderColor: '#BFDBFE',
                        borderRadius: 999,
                        paddingHorizontal: 10,
                        paddingVertical: 4,
                        flexDirection: 'row',
                        alignItems: 'center',
                        gap: 4,
                      }}
                    >
                      <Layers color="#2563EB" size={12} />
                      <Text
                        style={{
                          fontSize: 13,
                          fontWeight: '600',
                          color: '#2563EB',
                          fontFamily: 'Inter_600SemiBold',
                        }}
                      >
                        {log.pair_count} {log.pair_count === 1 ? 'inlegzool' : 'inlegzolen'}
                      </Text>
                    </View>
                  )}
                  <View
                    style={{
                      backgroundColor: '#F9FAFB',
                      borderWidth: 1,
                      borderColor: '#E5E7EB',
                      borderRadius: 999,
                      paddingHorizontal: 10,
                      paddingVertical: 4,
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 4,
                    }}
                  >
                    <Clock color="#111827" size={12} />
                    <Text
                      style={{
                        fontSize: 13,
                        fontWeight: '600',
                        color: '#111827',
                        fontFamily: 'Inter_600SemiBold',
                      }}
                    >
                      {formatDuration(log.duration_seconds)}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          ))
        )}
      </ScrollView>
    </View>
  );
}
