import { useState } from 'react';
import { View, Text, FlatList, TextInput, TouchableOpacity, ActivityIndicator, RefreshControl } from 'react-native';
import { useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { api } from '../../../services/api';

const STATUS_COLORS: Record<string, string> = {
  ACTIVE: '#16A34A', SUSPENDED: '#D97706', CANCELLED: '#DC2626', PENDING: '#6B7280',
};

export default function ClientsScreen() {
  const [search, setSearch] = useState('');
  const { data, isLoading, refetch, isRefetching } = useQuery({
    queryKey: ['clients'],
    queryFn: () => api.get('/api/v1/clients?limit=100').then(r => r.data?.data ?? r.data),
  });

  const clients = (data ?? []).filter((c: any) =>
    `${c.firstName} ${c.lastName} ${c.accountNumber}`.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <View className="flex-1 bg-gray-50">
      <View className="px-4 pt-14 pb-4 bg-primary">
        <Text className="text-white text-xl font-bold">Clients</Text>
      </View>
      <View className="px-4 py-3">
        <TextInput
          className="bg-white border border-gray-200 rounded-xl px-4 py-3 text-base"
          placeholder="Search name or account #"
          value={search}
          onChangeText={setSearch}
        />
      </View>
      {isLoading ? (
        <View className="flex-1 items-center justify-center">
          <ActivityIndicator color="#2563EB" />
        </View>
      ) : (
        <FlatList
          data={clients}
          keyExtractor={(item) => item.id}
          refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
          contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 24 }}
          renderItem={({ item }) => (
            <TouchableOpacity
              className="bg-white rounded-xl p-4 mb-2 border border-gray-100"
              onPress={() => router.push(`/(app)/clients/${item.id}`)}
            >
              <View className="flex-row justify-between items-start">
                <View className="flex-1">
                  <Text className="font-semibold text-gray-900">{item.firstName} {item.lastName}</Text>
                  <Text className="text-gray-500 text-sm">{item.accountNumber}</Text>
                  {item.phone && <Text className="text-gray-500 text-sm">{item.phone}</Text>}
                </View>
                <View className="rounded-full px-2 py-0.5" style={{ backgroundColor: `${STATUS_COLORS[item.status] ?? '#6B7280'}20` }}>
                  <Text className="text-xs font-medium" style={{ color: STATUS_COLORS[item.status] ?? '#6B7280' }}>
                    {item.status}
                  </Text>
                </View>
              </View>
            </TouchableOpacity>
          )}
          ListEmptyComponent={
            <View className="items-center py-16">
              <Text className="text-gray-400 text-base">No clients found</Text>
            </View>
          }
        />
      )}
    </View>
  );
}
