/**
 * Client list — FUB replacement contact list.
 * Searchable, filterable by lifecycle, pull-to-refresh.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { ClientsStackParamList } from '../../navigation/stacks/ClientsStack';
import { useTheme } from '../../themes/ThemeProvider';
import { getClients, Client } from '../../services/api';
import { getCachedData, cacheData, CacheKeys } from '../../services/offline';

type Props = NativeStackScreenProps<ClientsStackParamList, 'ClientList'>;

const LIFECYCLE_FILTERS = ['all', 'lead', 'active', 'closed', 'repeat'] as const;

export default function ClientList({ navigation }: Props) {
  const { theme } = useTheme();
  const [clients, setClients] = useState<Client[]>([]);
  const [search, setSearch] = useState('');
  const [filter, setFilter] = useState<string>('all');
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(true);

  const loadClients = useCallback(async () => {
    // Cache first
    const cached = await getCachedData<Client[]>(CacheKeys.CLIENTS);
    if (cached) {
      setClients(cached);
      setLoading(false);
    }

    const res = await getClients();
    if (res.success && res.data) {
      setClients(res.data);
      await cacheData(CacheKeys.CLIENTS, res.data, 60 * 60 * 1000);
    }
    setLoading(false);
  }, []);

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

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadClients();
    setRefreshing(false);
  }, [loadClients]);

  const filtered = clients.filter((c) => {
    const matchesFilter = filter === 'all' || c.lifecycle === filter;
    const matchesSearch =
      !search ||
      `${c.first_name} ${c.last_name}`.toLowerCase().includes(search.toLowerCase()) ||
      c.email?.toLowerCase().includes(search.toLowerCase()) ||
      c.phone?.includes(search);
    return matchesFilter && matchesSearch;
  });

  const lifecycleColor = (lc: string): string => {
    switch (lc) {
      case 'lead': return theme.colors.info;
      case 'active': return theme.colors.success;
      case 'closed': return theme.colors.accent;
      case 'repeat': return '#8B5CF6';
      default: return theme.colors.textSecondary;
    }
  };

  const renderClient = ({ item }: { item: Client }) => (
    <TouchableOpacity
      style={[styles.clientRow, { backgroundColor: theme.colors.card, borderBottomColor: theme.colors.border }]}
      onPress={() => navigation.navigate('ClientDetail', { id: item.id })}
    >
      <View style={[styles.avatar, { backgroundColor: theme.colors.primary }]}>
        <Text style={styles.avatarText}>
          {(item.first_name?.[0] ?? '').toUpperCase()}
          {(item.last_name?.[0] ?? '').toUpperCase()}
        </Text>
      </View>
      <View style={styles.clientInfo}>
        <Text style={[styles.clientName, { color: theme.colors.text }]}>
          {item.first_name} {item.last_name}
        </Text>
        <Text style={[styles.clientMeta, { color: theme.colors.textSecondary }]}>
          {item.email ?? item.phone ?? 'No contact info'}
        </Text>
      </View>
      <View style={styles.rightCol}>
        <View style={[styles.lifecycleBadge, { backgroundColor: lifecycleColor(item.lifecycle) + '20' }]}>
          <Text style={[styles.lifecycleText, { color: lifecycleColor(item.lifecycle) }]}>
            {item.lifecycle.toUpperCase()}
          </Text>
        </View>
        {item.lead_score > 0 && (
          <Text style={[styles.score, { color: theme.colors.textSecondary }]}>
            Score: {item.lead_score}
          </Text>
        )}
      </View>
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      {/* Search */}
      <View style={[styles.searchBar, { backgroundColor: theme.colors.surface }]}>
        <TextInput
          style={[styles.searchInput, { color: theme.colors.text, backgroundColor: theme.colors.inputBg }]}
          placeholder="Search clients..."
          placeholderTextColor={theme.colors.textSecondary}
          value={search}
          onChangeText={setSearch}
          autoCapitalize="none"
          autoCorrect={false}
        />
        <TouchableOpacity
          style={[styles.addBtn, { backgroundColor: theme.colors.primary }]}
          onPress={() => navigation.navigate('AddClient')}
        >
          <Text style={styles.addBtnText}>+</Text>
        </TouchableOpacity>
      </View>

      {/* Lifecycle Filters */}
      <View style={styles.filterRow}>
        {LIFECYCLE_FILTERS.map((f) => (
          <TouchableOpacity
            key={f}
            style={[
              styles.filterChip,
              {
                backgroundColor: filter === f ? theme.colors.primary : theme.colors.surface,
                borderColor: filter === f ? theme.colors.primary : theme.colors.border,
              },
            ]}
            onPress={() => setFilter(f)}
          >
            <Text
              style={[
                styles.filterText,
                { color: filter === f ? theme.colors.white : theme.colors.textSecondary },
              ]}
            >
              {f === 'all' ? 'All' : f.charAt(0).toUpperCase() + f.slice(1)}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* Client List */}
      <FlatList
        data={filtered}
        keyExtractor={(item) => String(item.id)}
        renderItem={renderClient}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
              {loading ? 'Loading clients...' : 'No clients found'}
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  searchBar: {
    flexDirection: 'row',
    padding: 12,
    gap: 10,
    alignItems: 'center',
  },
  searchInput: {
    flex: 1,
    height: 40,
    borderRadius: 10,
    paddingHorizontal: 14,
    fontSize: 15,
  },
  addBtn: {
    width: 40,
    height: 40,
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  addBtnText: {
    color: '#FFF',
    fontSize: 24,
    fontWeight: '300',
    marginTop: -2,
  },
  filterRow: {
    flexDirection: 'row',
    paddingHorizontal: 12,
    paddingBottom: 8,
    gap: 8,
  },
  filterChip: {
    paddingHorizontal: 14,
    paddingVertical: 6,
    borderRadius: 20,
    borderWidth: 1,
  },
  filterText: {
    fontSize: 13,
    fontWeight: '600',
  },
  clientRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  avatar: {
    width: 44,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  avatarText: {
    color: '#FFF',
    fontSize: 16,
    fontWeight: '700',
  },
  clientInfo: {
    flex: 1,
  },
  clientName: {
    fontSize: 16,
    fontWeight: '600',
  },
  clientMeta: {
    fontSize: 13,
    marginTop: 2,
  },
  rightCol: {
    alignItems: 'flex-end',
    gap: 4,
  },
  lifecycleBadge: {
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: 6,
  },
  lifecycleText: {
    fontSize: 10,
    fontWeight: '700',
  },
  score: {
    fontSize: 11,
  },
  empty: {
    padding: 40,
    alignItems: 'center',
  },
  emptyText: {
    fontSize: 15,
  },
});
