import { router } from 'expo-router';
import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, Pressable, ScrollView, StyleSheet, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

import { Button } from '@/components/button';
import { Card } from '@/components/card';
import { ScreenBackground } from '@/components/screen-background';
import { ThemedText } from '@/components/themed-text';
import { Spacing, TopTabInset } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { useAuth } from '@/lib/auth-context';
import { createPost, getFeed, type Post, type PostVisibility } from '@/lib/posts';
import {
  RELATIONSHIP_LABELS,
  type ConnectionRow,
  type ProfileResult,
  type RelationshipType,
  connectionStatusLabel,
  errorMessage,
  getConnectionStatuses,
  getIncomingRequests,
  getMyConnections,
  getProfileNames,
  respondToRequest,
  searchProfiles,
  sendConnectionRequest,
} from '@/lib/social';

const VISIBILITY_LABELS: Record<PostVisibility, string> = {
  connections: 'Conexiones',
  public: 'Público',
};

type Section = 'connections' | 'feed';

export default function SocialScreen() {
  const { session } = useAuth();
  const theme = useTheme();
  const userId = session!.user.id;

  const [view, setView] = useState<Section>('connections');
  const [error, setError] = useState<string | null>(null);

  const [query, setQuery] = useState('');
  const [results, setResults] = useState<ProfileResult[]>([]);
  const [resultStatuses, setResultStatuses] = useState<Map<string, ConnectionRow>>(new Map());
  const [pickingFor, setPickingFor] = useState<string | null>(null);
  const [incoming, setIncoming] = useState<ConnectionRow[]>([]);
  const [connections, setConnections] = useState<ConnectionRow[]>([]);
  const [names, setNames] = useState<Map<string, string>>(new Map());
  const [loadingConnections, setLoadingConnections] = useState(true);

  const [posts, setPosts] = useState<Post[]>([]);
  const [loadingFeed, setLoadingFeed] = useState(true);
  const [postContent, setPostContent] = useState('');
  const [postVisibility, setPostVisibility] = useState<PostVisibility>('connections');
  const [posting, setPosting] = useState(false);

  const loadRelations = useCallback(async () => {
    setLoadingConnections(true);
    try {
      const [incomingRows, connectionRows] = await Promise.all([
        getIncomingRequests(userId),
        getMyConnections(userId),
      ]);
      setIncoming(incomingRows);
      setConnections(connectionRows);

      const otherIds = new Set<string>();
      for (const c of [...incomingRows, ...connectionRows]) {
        otherIds.add(c.requester_id === userId ? c.addressee_id : c.requester_id);
      }
      setNames(await getProfileNames([...otherIds]));
    } catch (e) {
      setError(errorMessage(e));
    }
    setLoadingConnections(false);
  }, [userId]);

  const loadFeed = useCallback(async () => {
    setLoadingFeed(true);
    try {
      setPosts(await getFeed());
    } catch (e) {
      setError(errorMessage(e));
    }
    setLoadingFeed(false);
  }, []);

  useEffect(() => {
    loadRelations();
    loadFeed();
  }, [loadRelations, loadFeed]);

  async function runSearch() {
    setError(null);
    try {
      const found = await searchProfiles(query);
      setResults(found);
      setResultStatuses(await getConnectionStatuses(userId, found.map((r) => r.id)));
    } catch (e) {
      setError(errorMessage(e));
    }
  }

  async function handleSendRequest(addresseeId: string, relationshipType: RelationshipType) {
    setError(null);
    try {
      await sendConnectionRequest(userId, addresseeId, relationshipType);
      setPickingFor(null);
      setResultStatuses(await getConnectionStatuses(userId, results.map((r) => r.id)));
    } catch (e) {
      setError(errorMessage(e));
    }
  }

  async function handleRespond(connectionId: number, accept: boolean) {
    setError(null);
    try {
      await respondToRequest(connectionId, accept);
      await loadRelations();
    } catch (e) {
      setError(errorMessage(e));
    }
  }

  async function handlePost() {
    if (!postContent.trim()) return;
    setPosting(true);
    setError(null);
    try {
      await createPost(userId, postContent.trim(), postVisibility);
      setPostContent('');
      await loadFeed();
    } catch (e) {
      setError(errorMessage(e));
    }
    setPosting(false);
  }

  return (
    <ScreenBackground style={styles.container}>
      <SafeAreaView style={styles.safeArea}>
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <ThemedText type="title" style={styles.title}>
            Comunidad
          </ThemedText>

          <View style={styles.relationRow}>
            {(['connections', 'feed'] as Section[]).map((v) => (
              <Pressable
                key={v}
                onPress={() => setView(v)}
                style={[
                  styles.chip,
                  { borderColor: theme.tint },
                  view === v && { backgroundColor: theme.tint },
                ]}>
                <ThemedText type="small" themeColor={view === v ? 'background' : 'tint'}>
                  {v === 'connections' ? 'Conexiones' : 'Feed'}
                </ThemedText>
              </Pressable>
            ))}
          </View>

          {error && (
            <ThemedText type="small" themeColor="error">
              {error}
            </ThemedText>
          )}

          {view === 'connections' ? (
            <>
              <ThemedText type="smallBold">Buscar gente</ThemedText>
              <View style={styles.searchRow}>
                <TextInput
                  placeholder="Nombre..."
                  placeholderTextColor={theme.textSecondary}
                  value={query}
                  onChangeText={setQuery}
                  onSubmitEditing={runSearch}
                  style={[styles.input, { color: theme.text, borderColor: theme.text + '30' }]}
                />
                <Button label="Buscar" onPress={runSearch} style={styles.smallButton} />
              </View>

              {results.map((result) => {
                const existing = resultStatuses.get(result.id);
                return (
                  <Card key={result.id}>
                    <ThemedText type="smallBold">{result.display_name}</ThemedText>
                    {existing ? (
                      <ThemedText type="small" themeColor="textSecondary">
                        {connectionStatusLabel(userId, existing)}
                      </ThemedText>
                    ) : pickingFor === result.id ? (
                      <View style={styles.relationRow}>
                        {(Object.keys(RELATIONSHIP_LABELS) as RelationshipType[]).map((type) => (
                          <Pressable
                            key={type}
                            onPress={() => handleSendRequest(result.id, type)}
                            style={[styles.chip, { borderColor: theme.tint }]}>
                            <ThemedText type="small" themeColor="tint">
                              {RELATIONSHIP_LABELS[type]}
                            </ThemedText>
                          </Pressable>
                        ))}
                      </View>
                    ) : (
                      <Pressable onPress={() => setPickingFor(result.id)}>
                        <ThemedText type="link" themeColor="tint">
                          Conectar
                        </ThemedText>
                      </Pressable>
                    )}
                  </Card>
                );
              })}

              {loadingConnections ? (
                <ActivityIndicator />
              ) : (
                <>
                  <ThemedText type="smallBold">Solicitudes recibidas</ThemedText>
                  {incoming.length === 0 && (
                    <ThemedText type="small" themeColor="textSecondary">
                      No tienes solicitudes pendientes.
                    </ThemedText>
                  )}
                  {incoming.map((req) => (
                    <Card key={req.id}>
                      <ThemedText type="smallBold">{names.get(req.requester_id) ?? 'Alguien'}</ThemedText>
                      <ThemedText type="small" themeColor="textSecondary">
                        Quiere ser tu {RELATIONSHIP_LABELS[req.relationship_type]}
                      </ThemedText>
                      <View style={styles.relationRow}>
                        <Pressable onPress={() => handleRespond(req.id, true)}>
                          <ThemedText type="link" themeColor="tint">
                            Aceptar
                          </ThemedText>
                        </Pressable>
                        <Pressable onPress={() => handleRespond(req.id, false)}>
                          <ThemedText type="link" themeColor="error">
                            Rechazar
                          </ThemedText>
                        </Pressable>
                      </View>
                    </Card>
                  ))}

                  <ThemedText type="smallBold">Mis conexiones</ThemedText>
                  {connections.length === 0 && (
                    <ThemedText type="small" themeColor="textSecondary">
                      Todavía no tienes conexiones.
                    </ThemedText>
                  )}
                  {connections.map((c) => {
                    const otherId = c.requester_id === userId ? c.addressee_id : c.requester_id;
                    return (
                      <Card
                        key={c.id}
                        onPress={() => router.push({ pathname: '/profile/[id]', params: { id: otherId } })}>
                        <ThemedText type="smallBold">{names.get(otherId) ?? 'Alguien'}</ThemedText>
                        <ThemedText type="small" themeColor="textSecondary">
                          {RELATIONSHIP_LABELS[c.relationship_type]}
                        </ThemedText>
                      </Card>
                    );
                  })}
                </>
              )}
            </>
          ) : (
            <>
              <Card>
                <TextInput
                  placeholder="¿Qué lograste hoy en Colossus?"
                  placeholderTextColor={theme.textSecondary}
                  value={postContent}
                  onChangeText={setPostContent}
                  multiline
                  style={[styles.postInput, { color: theme.text, borderColor: theme.text + '30' }]}
                />
                <View style={styles.relationRow}>
                  {(Object.keys(VISIBILITY_LABELS) as PostVisibility[]).map((v) => (
                    <Pressable
                      key={v}
                      onPress={() => setPostVisibility(v)}
                      style={[
                        styles.chip,
                        { borderColor: theme.tint },
                        postVisibility === v && { backgroundColor: theme.tint },
                      ]}>
                      <ThemedText type="small" themeColor={postVisibility === v ? 'background' : 'tint'}>
                        {VISIBILITY_LABELS[v]}
                      </ThemedText>
                    </Pressable>
                  ))}
                </View>
                <Button label="Publicar" loading={posting} onPress={handlePost} style={styles.button} />
              </Card>

              {loadingFeed ? (
                <ActivityIndicator />
              ) : posts.length === 0 ? (
                <ThemedText type="small" themeColor="textSecondary">
                  Todavía no hay publicaciones. Sé el primero.
                </ThemedText>
              ) : (
                posts.map((post) => (
                  <Card key={post.id}>
                    <Pressable onPress={() => router.push({ pathname: '/profile/[id]', params: { id: post.user_id } })}>
                      <ThemedText type="smallBold" themeColor="tint">
                        {post.author_name}
                      </ThemedText>
                    </Pressable>
                    <ThemedText type="small">{post.content}</ThemedText>
                    <ThemedText type="small" themeColor="textSecondary">
                      {post.created_at.slice(0, 10)} · {VISIBILITY_LABELS[post.visibility]}
                    </ThemedText>
                  </Card>
                ))
              )}
            </>
          )}
        </ScrollView>
      </SafeAreaView>
    </ScreenBackground>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  safeArea: { flex: 1 },
  scrollContent: {
    paddingHorizontal: Spacing.four,
    paddingTop: Spacing.four + TopTabInset,
    paddingBottom: Spacing.six,
    gap: Spacing.three,
  },
  title: { fontSize: 32, lineHeight: 40 },
  searchRow: { flexDirection: 'row', gap: Spacing.two, alignItems: 'center' },
  input: {
    flex: 1,
    borderWidth: 1,
    borderRadius: Spacing.two,
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
    fontSize: 16,
  },
  postInput: {
    borderWidth: 1,
    borderRadius: Spacing.two,
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
    fontSize: 16,
    minHeight: 60,
    textAlignVertical: 'top',
  },
  smallButton: {
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
  },
  button: {},
  relationRow: { flexDirection: 'row', flexWrap: 'wrap', gap: Spacing.two },
  chip: {
    borderWidth: 1,
    borderRadius: Spacing.five,
    paddingHorizontal: Spacing.two,
    paddingVertical: Spacing.one,
  },
});
