import React, { useState, useEffect, useCallback } from 'react';
import {
  View, Text, StyleSheet, FlatList, ActivityIndicator, RefreshControl,
  TouchableOpacity,
} from 'react-native';
import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { storage } from '../utils/storage';

const API_URL = process.env.EXPO_PUBLIC_BACKEND_URL;

type Record = {
  date: string; action: string; time: string;
  location_url: string; is_auto_logout: boolean;
};

export default function HistoryScreen() {
  const router = useRouter();
  const [records, setRecords] = useState<Record[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const loadHistory = useCallback(async () => {
    try {
      const token = await storage.getItemAsync('token');
      const res = await fetch(`${API_URL}/api/attendance/history?days=30`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.status === 401) { router.replace('/'); return; }
      const data = await res.json();
      setRecords(data.records || []);
    } catch (e) {
      console.error('History error:', e);
    } finally { setLoading(false); setRefreshing(false); }
  }, []);

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

  // Group records by date
  const grouped = records.reduce((acc: { [key: string]: Record[] }, r) => {
    if (!acc[r.date]) acc[r.date] = [];
    acc[r.date].push(r);
    return acc;
  }, {});
  const dates = Object.keys(grouped).sort((a, b) => b.localeCompare(a));

  const renderItem = ({ item: date }: { item: string }) => {
    const dayRecords = grouped[date];
    const loginRec = dayRecords.find(r => r.action === 'Login');
    const logoutRec = dayRecords.find(r => r.action === 'Logout');
    return (
      <View style={styles.card}>
        <View style={styles.cardHeader}>
          <Text style={styles.cardDate}>{date}</Text>
          {logoutRec?.is_auto_logout && (
            <View style={styles.autoTag}>
              <Text style={styles.autoTagText}>AUTO</Text>
            </View>
          )}
        </View>
        <View style={styles.cardBody}>
          <View style={styles.timeRow}>
            <MaterialCommunityIcons name="login" size={18} color="#00C853" />
            <Text style={styles.timeLabel}>Login:</Text>
            <Text style={styles.timeValue}>{loginRec?.time || '--'}</Text>
          </View>
          <View style={styles.timeRow}>
            <MaterialCommunityIcons name="logout" size={18} color="#FF3D00" />
            <Text style={styles.timeLabel}>Logout:</Text>
            <Text style={styles.timeValue}>{logoutRec?.time || '--'}</Text>
          </View>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.safe}>
      <View style={styles.header}>
        <TouchableOpacity testID="history-back-btn" onPress={() => router.back()} style={styles.backBtn}>
          <MaterialCommunityIcons name="arrow-left" size={24} color="#00E5FF" />
        </TouchableOpacity>
        <Text style={styles.title}>Attendance History</Text>
      </View>

      {loading ? (
        <View style={styles.center}>
          <ActivityIndicator size="large" color="#00E5FF" />
        </View>
      ) : dates.length === 0 ? (
        <View style={styles.center}>
          <MaterialCommunityIcons name="calendar-blank" size={48} color="#475569" />
          <Text style={styles.emptyText}>No attendance records found</Text>
        </View>
      ) : (
        <FlatList
          data={dates}
          keyExtractor={(item) => item}
          renderItem={renderItem}
          contentContainerStyle={styles.list}
          refreshControl={
            <RefreshControl refreshing={refreshing}
              onRefresh={() => { setRefreshing(true); loadHistory(); }}
              tintColor="#00E5FF"
            />
          }
        />
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: '#050505' },
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  header: {
    flexDirection: 'row', alignItems: 'center', padding: 20,
    gap: 12, borderBottomWidth: 1, borderBottomColor: '#1E1E1E',
  },
  backBtn: { padding: 4 },
  title: { color: '#FFF', fontSize: 20, fontWeight: '700' },
  list: { padding: 20 },
  card: {
    backgroundColor: '#121212', borderLeftWidth: 4, borderLeftColor: '#475569',
    padding: 16, marginBottom: 12, borderRadius: 2,
  },
  cardHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 },
  cardDate: { color: '#E5E7EB', fontSize: 15, fontWeight: '600' },
  autoTag: {
    backgroundColor: '#FFD600', paddingHorizontal: 8, paddingVertical: 2, borderRadius: 2,
  },
  autoTagText: { color: '#000', fontSize: 10, fontWeight: '700' },
  cardBody: { gap: 8 },
  timeRow: { flexDirection: 'row', alignItems: 'center', gap: 8 },
  timeLabel: { color: '#B0B0B0', fontSize: 13, width: 60 },
  timeValue: { color: '#FFF', fontSize: 14, fontWeight: '500' },
  emptyText: { color: '#6E6E6E', fontSize: 16, marginTop: 12 },
});
