import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Modal, FlatList, ActivityIndicator, TextInput } from 'react-native';
import { useSettings } from '@/theme';
import { useFriends } from '@/hooks/useFriends';

interface AssigneeSelectorProps {
  value: string | null;
  onChange: (assigneeId: string | null) => void;
  disabled?: boolean;
  friends: string[];
}

export function AssigneeSelector({ value, onChange, disabled = false }: AssigneeSelectorProps) {
  const { theme } = useSettings();
  const { friends, searchUsers, loading: friendsLoading } = useFriends();
  const [showModal, setShowModal] = React.useState(false);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [searchResults, setSearchResults] = React.useState<Array<{ id: string; username: string }>>([]);
  const [searching, setSearching] = React.useState(false);

  const selectedFriend = value ? friends.find(f => f.id === value) : null;

  React.useEffect(() => {
    if (showModal && searchQuery.length >= 2) {
      const timeout = setTimeout(async () => {
        setSearching(true);
        try {
          const results = await searchUsers(searchQuery);
          setSearchResults(results.filter(r => !friends.some(f => f.id === r.id)));
        } catch (err) {
          console.error('Search failed:', err);
        } finally {
          setSearching(false);
        }
      }, 300);
      return () => clearTimeout(timeout);
    } else {
      setSearchResults([]);
    }
  }, [searchQuery, showModal, friends, searchUsers]);

  const handleSelectFriend = (friendId: string) => {
    onChange(friendId);
    setShowModal(false);
  };

  const handleClear = () => {
    onChange(null);
  };

  const handleSearchAdd = async (friendId: string, username: string) => {
    try {
      const { sendFriendRequest } = await import('@/services/friends');
      await sendFriendRequest(username);
      onChange(friendId);
      setShowModal(false);
    } catch (err) {
      console.error('Failed to add friend:', err);
    }
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={[
          styles.selectorButton,
          { backgroundColor: theme.inputBg, borderColor: theme.borderStrong },
          disabled && { opacity: 0.6 },
        ]}
        onPress={() => !disabled && setShowModal(true)}
        activeOpacity={0.8}
      >
        <Text style={[styles.selectorIcon, { color: theme.accent }]}>👤</Text>
        <View style={styles.selectorContent}>
          <Text style={[styles.selectorLabel, { color: theme.textMuted }]}>Assignee</Text>
          <Text
            style={[
              styles.selectorValue,
              { color: value ? theme.text : theme.textMuted },
            ]}
          >
            {selectedFriend ? selectedFriend.username : 'Unassigned'}
          </Text>
        </View>
        {value && !disabled && (
          <TouchableOpacity
            style={styles.clearButton}
            onPress={(e) => {
              e.stopPropagation();
              handleClear();
            }}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
          >
            <Text style={[styles.clearText, { color: theme.textMuted }]}>✕</Text>
          </TouchableOpacity>
        )}
      </TouchableOpacity>

      <Modal visible={showModal} transparent animationType="fade" onRequestClose={() => setShowModal(false)}>
        <View style={[styles.modalOverlay, { backgroundColor: 'rgba(0,0,0,0.5)' }]}>
          <View style={[styles.modalSheet, { backgroundColor: theme.sheetBg }]}>
            <View style={styles.modalHeader}>
              <Text style={[styles.modalTitle, { color: theme.text }]}>Assign Task</Text>
              <TouchableOpacity onPress={() => setShowModal(false)} hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
                <Text style={[styles.closeText, { color: theme.textMuted }]}>✕</Text>
              </TouchableOpacity>
            </View>

            <View style={styles.modalSection}>
              <TouchableOpacity
                style={[
                  styles.optionRow,
                  { backgroundColor: selectedFriend ? theme.accentSoft : 'transparent', borderColor: selectedFriend ? theme.accent : 'transparent' },
                ]}
                onPress={() => handleClear()}
              >
                <View style={styles.optionIcon}>
                  <Text style={styles.optionIconText}>🚫</Text>
                </View>
                <Text style={[styles.optionText, { color: theme.text }]}>Unassigned</Text>
                {selectedFriend && (
                  <Text style={[styles.checkmark, { color: theme.accent }]}>✓</Text>
                )}
              </TouchableOpacity>
            </View>

            <View style={styles.modalSection}>
              <Text style={[styles.sectionTitle, { color: theme.textMuted }]}>Friends</Text>
              {friendsLoading ? (
                <View style={styles.loading}>
                  <ActivityIndicator color={theme.accent} size="large" />
                </View>
              ) : friends.length === 0 ? (
                <Text style={[styles.emptyText, { color: theme.textFaint }]}>No friends yet. Add friends to assign tasks.</Text>
              ) : (
                <FlatList
                  data={friends}
                  keyExtractor={f => f.id}
                  renderItem={({ item }) => (
                    <TouchableOpacity
                      style={[
                        styles.optionRow,
                        { backgroundColor: value === item.id ? theme.accentSoft : 'transparent', borderColor: value === item.id ? theme.accent : 'transparent' },
                      ]}
                      onPress={() => handleSelectFriend(item.id)}
                    >
                      <View style={styles.optionIcon}>
                        <Text style={styles.optionIconText}>👤</Text>
                      </View>
                      <Text style={[styles.optionText, { color: theme.text }]}>{item.username}</Text>
                      {value === item.id && (
                        <Text style={[styles.checkmark, { color: theme.accent }]}>✓</Text>
                      )}
                    </TouchableOpacity>
                  )}
                />
              )}
            </View>

            <View style={styles.modalSection}>
              <View style={styles.searchContainer}>
                <TextInput
                  style={[styles.searchInput, { backgroundColor: theme.inputBg, borderColor: theme.borderStrong, color: theme.text }]}
                  placeholder="Search users by username"
                  placeholderTextColor={theme.textMuted}
                  value={searchQuery}
                  onChangeText={setSearchQuery}
                  autoCapitalize="none"
                  autoCorrect={false}
                />
              </View>
              {searching ? (
                <View style={styles.loading}>
                  <ActivityIndicator color={theme.accent} size="large" />
                </View>
              ) : searchQuery.length >= 2 && searchResults.length > 0 ? (
                <FlatList
                  data={searchResults}
                  keyExtractor={u => u.id}
                  renderItem={({ item }) => (
                    <TouchableOpacity
                      style={styles.optionRow}
                      onPress={() => handleSearchAdd(item.id, item.username)}
                    >
                      <View style={styles.optionIcon}>
                        <Text style={styles.optionIconText}>➕</Text>
                      </View>
                      <Text style={[styles.optionText, { color: theme.text }]}>{item.username}</Text>
                      <Text style={[styles.optionSubtext, { color: theme.textMuted }]}>Add as friend & assign</Text>
                    </TouchableOpacity>
                  )}
                />
              ) : searchQuery.length >= 2 && searchResults.length === 0 && !searching ? (
                <Text style={[styles.emptyText, { color: theme.textFaint }]}>No users found</Text>
              ) : searchQuery.length < 2 ? (
                <Text style={[styles.emptyText, { color: theme.textFaint }]}>Type at least 2 characters to search</Text>
              ) : null}
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    width: '100%',
  },
  selectorButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
    paddingVertical: 14,
    paddingHorizontal: 12,
    borderRadius: 12,
    borderWidth: 1,
    minHeight: 52,
  },
  selectorIcon: {
    fontSize: 20,
  },
  selectorContent: {
    flex: 1,
    justifyContent: 'center',
  },
  selectorLabel: {
    fontSize: 11,
    fontWeight: '600',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 2,
  },
  selectorValue: {
    fontSize: 15,
    fontWeight: '500',
  },
  clearButton: {
    padding: 4,
  },
  clearText: {
    fontSize: 18,
    fontWeight: '300',
  },
  modalOverlay: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  modalSheet: {
    width: '100%',
    maxWidth: 400,
    borderRadius: 20,
    overflow: 'hidden',
    maxHeight: '85%',
  },
  modalHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 20,
    borderBottomWidth: 1,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: '700',
  },
  closeText: {
    fontSize: 22,
    fontWeight: '300',
  },
  modalSection: {
    padding: 12,
    paddingBottom: 20,
    borderBottomWidth: 1,
  },
  sectionTitle: {
    fontSize: 12,
    fontWeight: '600',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 8,
    paddingHorizontal: 8,
  },
  optionRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 10,
    borderWidth: 1,
  },
  optionIcon: {
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0,0,0,0.05)',
  },
  optionIconText: {
    fontSize: 16,
  },
  optionText: {
    fontSize: 16,
    fontWeight: '500',
    flex: 1,
  },
  optionSubtext: {
    fontSize: 12,
    marginTop: 2,
  },
  checkmark: {
    fontSize: 18,
    fontWeight: '700',
  },
  loading: {
    padding: 20,
    alignItems: 'center',
  },
  emptyText: {
    fontSize: 14,
    textAlign: 'center',
    paddingHorizontal: 20,
  },
  searchContainer: {
    padding: 12,
    paddingBottom: 8,
  },
  searchInput: {
    fontSize: 16,
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 12,
    borderWidth: 1,
  },
});