import React, { useEffect, useState } from 'react';
import {
  Text,
  View,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import Icon from 'react-native-vector-icons/Ionicons';
import { getStyles } from './leads.styles';
import { useTheme } from '@theme';
import { useAppDispatch, useAppSelector, RootState } from '@store';
import { getLeads } from './thunk';
import { LeadItem } from '@interfaces';
import { LeadItemCard, SearchInput, Loader } from '@components';
import { LeadsStackParamList } from '../../navigation/leadsStack';
import { route } from '@utils';

type LeadsScreenNavigationProp = NativeStackNavigationProp<
  LeadsStackParamList,
  'leads'
>;

export const LeadsScreen = () => {
  const dispatch = useAppDispatch();
  const navigation = useNavigation<LeadsScreenNavigationProp>();
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);
  const [searchTerm, setSearchTerm] = useState('');

  const { items, loading, error } = useAppSelector(
    (state: RootState) => state.leads,
  );
  const user_data = useAppSelector((state: RootState) => state.auth.user_data);

  useEffect(() => {
    if (user_data?.staffid) {
      dispatch(getLeads({ leadId: null, staffid: user_data.staffid }));
    }
  }, [dispatch, user_data]);

  const filteredLeads = searchTerm
    ? items.filter(
        lead =>
          lead.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          lead.company.toLowerCase().includes(searchTerm.toLowerCase()) ||
          lead.email.toLowerCase().includes(searchTerm.toLowerCase()),
      )
    : items;

  const handleLeadPress = (lead: LeadItem) => {
    // Navigate to lead details screen
    navigation.navigate(route.leadDetails, { lead });
  };

  const renderLead = ({ item }: { item: LeadItem }) => (
    <LeadItemCard item={item} onPress={() => handleLeadPress(item)} />
  );

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <SearchInput
          value={searchTerm}
          onChangeText={setSearchTerm}
          placeholder="Search leads, companies, emails..."
          style={styles.searchInput}
        />
        <TouchableOpacity style={styles.filterButton}>
          <Icon name="filter-outline" size={20} color={colors.text} />
        </TouchableOpacity>
      </View>

      {loading ? (
        <Loader message="Loading leads..." />
      ) : error ? (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      ) : (
        <FlatList
          data={filteredLeads}
          keyExtractor={item => item.id}
          contentContainerStyle={styles.listContent}
          renderItem={renderLead}
          ListEmptyComponent={() => (
            <View style={styles.emptyContainer}>
              <Text style={styles.emptyText}>No leads available.</Text>
            </View>
          )}
        />
      )}
    </View>
  );
};
