import React, { useState, useCallback } from 'react';
import { View, Text, FlatList, StyleSheet, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { ScreenListContainer } from '../../components/layout/ScreenContainer';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { EmptyState } from '../../components/ui/EmptyState';
import { useResponsive } from '../../hooks/useResponsive';
import { auditService, AuditLog, AuditPagination } from '../../services/auditService';
import { colors, spacing, radii } from '../../theme';

const ACTION_COLORS: Record<string, string> = {
  CREATE: colors.success[600],
  ASSIGN: colors.info[600],
  STATUS_CHANGE: colors.warning[600],
  CHECK_IN: colors.primary[600],
  CHECK_OUT: colors.primary[500],
  UPDATE: colors.warning[600],
  DELETE: colors.danger[600],
};

const ACTION_ICONS: Record<string, keyof typeof Ionicons.glyphMap> = {
  CREATE: 'add-circle-outline',
  ASSIGN: 'person-add-outline',
  STATUS_CHANGE: 'swap-horizontal-outline',
  CHECK_IN: 'log-in-outline',
  CHECK_OUT: 'log-out-outline',
  UPDATE: 'create-outline',
  DELETE: 'trash-outline',
};

export default function AuditLogScreen() {
  const navigation = useNavigation<any>();
  const { contentPadding, fontSize } = useResponsive();
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [pagination, setPagination] = useState<AuditPagination>({ page: 1, limit: 50, total: 0, pages: 0 });
  const [selectedAction, setSelectedAction] = useState<string | undefined>();
  const [selectedEntity, setSelectedEntity] = useState<string | undefined>();

  const loadLogs = async (page = 1) => {
    try {
      const result = await auditService.list({
        action: selectedAction,
        entity_type: selectedEntity,
        page,
        limit: 20,
      });
      if (page === 1) {
        setLogs(result.data);
      } else {
        setLogs(prev => [...prev, ...result.data]);
      }
      setPagination(result.pagination);
    } catch (error) {
      console.error('Failed to load audit logs:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => {
    setLoading(true);
    loadLogs(1);
  }, [selectedAction, selectedEntity]));

  const onRefresh = () => {
    setRefreshing(true);
    loadLogs(1);
  };

  const loadMore = () => {
    if (pagination.page < pagination.pages) {
      loadLogs(pagination.page + 1);
    }
  };

  const formatValue = (val: any): string => {
    if (!val) return '-';
    if (typeof val === 'string') {
      try {
        const parsed = JSON.parse(val);
        return JSON.stringify(parsed, null, 0).substring(0, 100);
      } catch {
        return val.substring(0, 100);
      }
    }
    return JSON.stringify(val).substring(0, 100);
  };

  const formatAction = (action: string): string => {
    return action.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
  };

  const formatDate = (dateStr: string): string => {
    const d = new Date(dateStr);
    const now = new Date();
    const diff = now.getTime() - d.getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return 'Just now';
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    const days = Math.floor(hrs / 24);
    if (days < 7) return `${days}d ago`;
    return d.toLocaleDateString();
  };

  const filterBar = (
    <View style={[styles.filterBar, { paddingHorizontal: contentPadding }]}>
      <FlatList
        horizontal
        showsHorizontalScrollIndicator={false}
        data={[
          { label: 'All', value: undefined },
          { label: 'Create', value: 'CREATE' },
          { label: 'Assign', value: 'ASSIGN' },
          { label: 'Status', value: 'STATUS_CHANGE' },
          { label: 'Check-in', value: 'CHECK_IN' },
          { label: 'Check-out', value: 'CHECK_OUT' },
        ]}
        keyExtractor={(item) => item.label}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={[styles.filterChip, selectedAction === item.value && styles.filterChipActive]}
            onPress={() => setSelectedAction(item.value)}
          >
            <Text style={[styles.filterChipText, { fontSize: fontSize.bodySmall }, selectedAction === item.value && styles.filterChipTextActive]}>
              {item.label}
            </Text>
          </TouchableOpacity>
        )}
        contentContainerStyle={{ gap: spacing.sm }}
      />
    </View>
  );

  return (
    <ScreenListContainer
      title="Audit Log"
      subtitle={`${pagination.total} records`}
      onBack={() => navigation.goBack()}
      loading={loading}
      refreshing={refreshing}
      onRefresh={onRefresh}
      data={logs}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item, index }) => {
        const actionColor = ACTION_COLORS[item.action] || colors.gray[500];
        const actionIcon = ACTION_ICONS[item.action] || 'ellipse-outline';
        return (
          <AnimatedCard delay={index * 40} style={{ marginBottom: spacing.sm }}>
            <View style={styles.logRow}>
              <View style={[styles.iconContainer, { backgroundColor: `${actionColor}15` }]}>
                <Ionicons name={actionIcon} size={18} color={actionColor} />
              </View>
              <View style={styles.logInfo}>
                <View style={styles.logHeader}>
                  <Text style={[styles.logAction, { fontSize: fontSize.body, color: actionColor }]}>
                    {formatAction(item.action)}
                  </Text>
                  <Text style={[styles.logTime, { fontSize: fontSize.caption }]}>
                    {formatDate(item.created_at)}
                  </Text>
                </View>
                <Text style={[styles.logEntity, { fontSize: fontSize.bodySmall }]}>
                  {item.entity_type} #{item.entity_id || ''}
                  {item.first_name ? ` by ${item.first_name} ${item.last_name}` : ''}
                </Text>
                {item.new_value && (
                  <Text style={[styles.logDetail, { fontSize: fontSize.caption }]} numberOfLines={1}>
                    {formatValue(item.new_value)}
                  </Text>
                )}
              </View>
            </View>
          </AnimatedCard>
        );
      }}
      toolbar={filterBar}
      ListEmptyComponent={
        <EmptyState
          icon="document-text-outline"
          title="No audit logs"
          description="Activity will appear here"
        />
      }
      ListFooterComponent={
        pagination.page < pagination.pages ? (
          <TouchableOpacity style={styles.loadMore} onPress={loadMore}>
            <Text style={[styles.loadMoreText, { fontSize: fontSize.bodySmall }]}>Load more</Text>
          </TouchableOpacity>
        ) : undefined
      }
    />
  );
}

const styles = StyleSheet.create({
  filterBar: {
    paddingVertical: spacing.md,
  },
  filterChip: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: radii.full,
    backgroundColor: colors.white,
    borderWidth: 1,
    borderColor: colors.border,
  },
  filterChipActive: {
    backgroundColor: colors.primary[600],
    borderColor: colors.primary[600],
  },
  filterChipText: {
    fontWeight: '500',
    color: colors.gray[600],
  },
  filterChipTextActive: {
    color: colors.white,
  },
  logRow: {
    flexDirection: 'row',
    gap: spacing.md,
  },
  iconContainer: {
    width: 36,
    height: 36,
    borderRadius: radii.md,
    justifyContent: 'center',
    alignItems: 'center',
  },
  logInfo: { flex: 1 },
  logHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 2,
  },
  logAction: { fontWeight: '600' },
  logTime: { color: colors.gray[400] },
  logEntity: { color: colors.gray[600], marginBottom: 2 },
  logDetail: { color: colors.gray[400], fontFamily: 'monospace' },
  loadMore: {
    padding: spacing.lg,
    alignItems: 'center',
  },
  loadMoreText: { color: colors.primary[600], fontWeight: '600' },
});
