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

const STATUS_COLOR: Record<string, string> = {
  active: '#16A34A', suspended: '#DC2626', pending: '#D97706', cancelled: '#6B7280',
};

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

  const filtered = (data ?? []).filter((c: any) =>
    [c.firstName, c.lastName, c.accountNumber, c.phone].join(' ').toLowerCase().includes(search.toLowerCase())
  );

  return (
    <View className="flex-1 bg-gray-50">
      <View className="px-4 pt-14 pb-3 bg-white border-b border-gray-100">
        <Text className="text-xl font-bold text-gray-900 mb-3">Clients</Text>
        <TextInput
          className="bg-gray-100 rounded-xl px-4 py-2 text-base"
          placeholder="Search name, account #, phone..."
          value={search}
          onChangeText={setSearch}
        />
      </View>

      {isLoading ? (
        <View className="flex-1 items-center justify-center">
          <ActivityIndicator color="#2563EB" />
        </View>
      ) : (
        <FlatList
          data={filtered}
          keyExtractor={(item) => item.id}
          contentContainerStyle={{ padding: 16 }}
          renderItem={({ item }) => (
            <TouchableOpacity
              className="bg-white rounded-xl p-4 mb-2 border border-gray-100 flex-row items-center"
              onPress={() => router.push(`/(app)/clients/${item.id}`)}
            >
              <View className="w-10 h-10 rounded-full bg-blue-100 items-center justify-center mr-3">
                <Text className="text-primary font-bold">{item.firstName?.[0]?.toUpperCase()}</Text>
              </View>
              <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} · {item.phone}</Text>
              </View>
              <View className="px-2 py-1 rounded-full" style={{ backgroundColor: `${STATUS_COLOR[item.status] ?? '#6B7280'}20` }}>
                <Text className="text-xs font-medium capitalize" style={{ color: STATUS_COLOR[item.status] ?? '#6B7280' }}>
                  {item.status}
                </Text>
              </View>
            </TouchableOpacity>
          )}
          ListEmptyComponent={
            <View className="items-center py-20">
              <Text className="text-gray-400">No clients found</Text>
            </View>
          }
        />
      )}
    </View>
  );
}
