import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { InboxStackParamList } from '../../navigation/types';
import { COLORS, FONT_SIZE, SPACING, RADIUS, TEXT } from '../../theme';
import { useTheme } from '../../theme';
import { Spinner, EmptyState, Button } from '../../components/ui';
import { inboxAPI } from '../../services/api';
import { Message } from '../../types';
import { useToast } from '../../contexts/ToastContext';
import { useTranslation } from '../../i18n';

type Props = NativeStackScreenProps<InboxStackParamList, 'Conversation'>;

export function ConversationScreen({ route, navigation }: Props) {
  const { conversationId } = route.params;
  const { theme } = useTheme();
  const { t } = useTranslation();
  const toast = useToast();
  const qc = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['conversation', conversationId],
    queryFn: () => inboxAPI.getConversation(conversationId),
  });

  const deleteMutation = useMutation({
    mutationFn: () => inboxAPI.deleteConversation(conversationId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['inbox'] });
      toast.success(t.inbox.delete);
      navigation.goBack();
    },
  });

  const handleDelete = () => {
    Alert.alert(t.inbox.delete, t.inbox.delete_confirm, [
      { text: t.common.cancel, style: 'cancel' },
      { text: t.common.delete, style: 'destructive', onPress: () => deleteMutation.mutate() },
    ]);
  };

  const messages: Message[] = data?.messages ?? [];

  const renderMessage = ({ item }: { item: Message }) => {
    const isUser = item.role === 'user';
    return (
      <View style={[styles.msgRow, isUser && styles.msgRowUser]}>
        {!isUser && (
          <View style={[styles.botAvatar, { backgroundColor: COLORS.primaryUltraLight }]}>
            <Text style={[styles.botAvatarText, { color: COLORS.primaryDark }]}>AI</Text>
          </View>
        )}
        <View style={[
          styles.bubble,
          isUser
            ? [styles.bubbleUser, { backgroundColor: COLORS.primary }]
            : [styles.bubbleBot, { backgroundColor: theme.surface, borderColor: theme.border }],
        ]}>
          <Text style={[styles.bubbleText, { color: isUser ? '#fff' : theme.text }]}>
            {item.content}
          </Text>
          {!isUser && item.confidence_score != null && (
            <Text style={[styles.confidence, { color: theme.textMuted }]}>
              Confidence: {(item.confidence_score * 100).toFixed(0)}%
            </Text>
          )}
          {item.is_handoff && (
            <Text style={styles.handoffTag}>⚡ Handoff requested</Text>
          )}
          {item.created_at ? (
            <Text style={[styles.timestamp, { color: isUser ? 'rgba(255,255,255,0.6)' : theme.textMuted }]}>
              {new Date(item.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </Text>
          ) : null}
        </View>
      </View>
    );
  };

  if (isLoading) return <Spinner centered />;

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      <View style={[styles.header, { borderBottomColor: theme.border, backgroundColor: theme.surface }]}>
        <View>
          <Text style={[styles.headerTitle, { color: theme.text }]}>
            {data?.chatbot_name ?? 'Conversation'}
          </Text>
          <Text style={[styles.headerSub, { color: theme.textSecondary }]}>
            {messages.length} {t.inbox.filter_all.toLowerCase()}
          </Text>
        </View>
        <Button
          title={t.inbox.delete}
          variant="danger"
          size="sm"
          onPress={handleDelete}
          loading={deleteMutation.isPending}
        />
      </View>

      <FlatList
        data={messages}
        keyExtractor={item => item.id}
        renderItem={renderMessage}
        contentContainerStyle={styles.list}
        showsVerticalScrollIndicator={false}
        ListEmptyComponent={
          <EmptyState
            title={t.inbox.no_messages}
            description={t.inbox.empty_desc}
          />
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
  },
  headerTitle: { ...TEXT.h4 },
  headerSub: { ...TEXT.small },

  list: { padding: SPACING.md, gap: SPACING.md, paddingBottom: SPACING.xl },

  msgRow: { flexDirection: 'row', gap: SPACING.sm, alignItems: 'flex-end' },
  msgRowUser: { flexDirection: 'row-reverse' },

  botAvatar: { width: 30, height: 30, borderRadius: RADIUS.full, alignItems: 'center', justifyContent: 'center' },
  botAvatarText: { fontSize: 10, fontWeight: '700' },

  bubble: { maxWidth: '75%', borderRadius: RADIUS.xl, padding: SPACING.md, gap: 4 },
  bubbleUser: { borderBottomRightRadius: RADIUS.sm },
  bubbleBot: { borderWidth: 1, borderBottomLeftRadius: RADIUS.sm },
  bubbleText: { fontSize: FONT_SIZE.md, lineHeight: 22 },

  confidence: { fontSize: FONT_SIZE.xs },
  handoffTag: { fontSize: FONT_SIZE.xs, color: COLORS.warning, fontWeight: '600' },
  timestamp: { fontSize: 10 },
});
