import React, { useEffect, useState } from 'react';
import {
  View, Text, FlatList, StyleSheet,
  ActivityIndicator, Alert, TouchableOpacity,
} from 'react-native';
import { adminFetchUsers } from '../../services/api';

interface UserRecord {
  id: string;
  name: string;
  email: string;
  phone?: string | null;
  address?: string | null;
  role: string;
  created_at: string;
  order_count: number;
}

export default function ManageUsersScreen() {
  const [users, setUsers]     = useState<UserRecord[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadUsers = async () => {
    setLoading(true);
    try { setUsers(await adminFetchUsers()); }
    catch { Alert.alert('Error', 'Could not load users.'); }
    finally { setLoading(false); }
  };

  const renderItem = ({ item }: { item: UserRecord }) => (
    <View style={styles.card}>
      <View style={styles.cardTop}>
        <Text style={styles.name}>{item.name}</Text>
        <View style={[styles.badge, item.role === 'admin' ? styles.adminBadge : styles.custBadge]}>
          <Text style={[styles.badgeText, item.role === 'admin' ? styles.adminText : styles.custText]}>
            {item.role.toUpperCase()}
          </Text>
        </View>
      </View>
      <Text style={styles.email}>✉️ {item.email}</Text>
      {item.phone && <Text style={styles.info}>📞 {item.phone}</Text>}
      {item.address && <Text style={styles.info}>📍 {item.address}</Text>}
      <Text style={styles.orders}>📦 {item.order_count} order{item.order_count !== 1 ? 's' : ''}</Text>
      <Text style={styles.date}>Joined {new Date(item.created_at).toLocaleDateString()}</Text>
    </View>
  );

  return (
    <View style={styles.bg}>
      <View style={styles.header}>
        <Text style={styles.title}>👥 Customers</Text>
        <TouchableOpacity onPress={loadUsers}>
          <Text style={styles.refresh}>↻ Refresh</Text>
        </TouchableOpacity>
      </View>
      {loading
        ? <ActivityIndicator color="#f97316" size="large" style={{ marginTop: 40 }} />
        : (
          <FlatList
            data={users}
            keyExtractor={(i: UserRecord) => i.id}
            renderItem={renderItem}
            contentContainerStyle={styles.list}
            ListEmptyComponent={<Text style={styles.empty}>No users found.</Text>}
          />
        )
      }
    </View>
  );
}

const styles = StyleSheet.create({
  bg:         { flex: 1, backgroundColor: '#0f172a' },
  header:     { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16 },
  title:      { fontSize: 20, fontWeight: '700', color: '#fff' },
  refresh:    { color: '#f97316', fontWeight: '700' },
  list:       { padding: 16, paddingTop: 0 },
  card:       { backgroundColor: '#1e293b', borderRadius: 14, padding: 16, marginBottom: 12 },
  cardTop:    { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 },
  name:       { color: '#fff', fontWeight: '700', fontSize: 16 },
  badge:      { borderRadius: 6, paddingHorizontal: 10, paddingVertical: 3, alignSelf: 'flex-start' },
  adminBadge: { backgroundColor: 'rgba(249,115,22,0.15)' },
  custBadge:  { backgroundColor: 'rgba(59,130,246,0.15)' },
  badgeText:  { fontWeight: '700', fontSize: 11 },
  adminText:  { color: '#f97316' },
  custText:   { color: '#3b82f6' },
  email:      { color: '#94a3b8', fontSize: 13, marginBottom: 2 },
  info:       { color: '#64748b', fontSize: 12, marginBottom: 2 },
  orders:     { color: '#f97316', fontWeight: '700', fontSize: 13, marginTop: 6 },
  date:       { color: '#475569', fontSize: 11, marginTop: 2 },
  empty:      { color: '#64748b', textAlign: 'center', marginTop: 40 },
});
