import React, { useRef, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl,
  Animated,
  ScrollView,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery } from '@tanstack/react-query';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { InboxStackParamList } from '../../navigation/types';
import { COLORS, FONT_SIZE, SPACING, RADIUS, TEXT, SHADOWS } from '../../theme';
import { useTheme } from '../../theme';
import { Spinner, EmptyState } from '../../components/ui';
import { inboxAPI } from '../../services/api';
import { useTranslation } from '../../i18n';
import { Conversation } from '../../types';

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

type StatusFilter = 'all' | 'open' | 'agent_handling' | 'resolved';

const STATUS_COLORS: Record<string, string> = {
  open: COLORS.success,
  agent_handling: COLORS.warning,
  resolved: COLORS.info,
};

export function InboxScreen({ navigation }: Props) {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');

  const FILTERS: { key: StatusFilter; label: string }[] = [
    { key: 'all', label: t.inbox.filter_all },
    { key: 'open', label: t.inbox.filter_open },
    { key: 'agent_handling', label: t.inbox.filter_handling },
    { key: 'resolved', label: t.inbox.filter_resolved },
  ];

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['inbox', statusFilter],
    queryFn: () =>
      inboxAPI.listConversations({
        limit: 50,
        ...(statusFilter !== 'all' ? { status: statusFilter } : {}),
      }),
  });

  const conversations: Conversation[] = data?.conversations ?? data?.items ?? data ?? [];

  const formatTime = (iso?: string) => {
    if (!iso) return '';
    const d = new Date(iso);
    const now = new Date();
    const diffH = (now.getTime() - d.getTime()) / 3600000;
    if (diffH < 24) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    if (diffH < 48) return 'Yesterday';
    return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
  };

  const renderItem = ({ item }: { item: Conversation }) => (
    <ConversationRow
      item={item}
      time={formatTime(item.created_at)}
      onPress={() => navigation.navigate('Conversation', {
        conversationId: item.id,
        chatbotName: item.chatbot_name,
      })}
      theme={theme}
    />
  );

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      <View style={[styles.header, { borderBottomColor: theme.border }]}>
        <Text style={[styles.headerTitle, { color: theme.text }]}>{t.inbox.title}</Text>
        {conversations.length > 0 && (
          <View style={[styles.countBadge, { backgroundColor: COLORS.primaryUltraLight }]}>
            <Text style={[styles.countBadgeText, { color: COLORS.primaryDark }]}>{conversations.length}</Text>
          </View>
        )}
      </View>

      {/* Status filter tabs */}
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        style={[styles.filterBar, { borderBottomColor: theme.border }]}
        contentContainerStyle={styles.filterBarContent}>
        {FILTERS.map(f => (
          <TouchableOpacity
            key={f.key}
            style={[
              styles.filterTab,
              statusFilter === f.key && { borderBottomColor: COLORS.primary, borderBottomWidth: 2 },
            ]}
            onPress={() => setStatusFilter(f.key)}>
            <Text style={[
              styles.filterTabText,
              { color: statusFilter === f.key ? COLORS.primary : theme.textSecondary },
              statusFilter === f.key && { fontWeight: '700' },
            ]}>
              {f.label}
            </Text>
          </TouchableOpacity>
        ))}
      </ScrollView>

      {isLoading ? (
        <Spinner centered label={t.common.loading} />
      ) : (
        <FlatList
          data={conversations}
          keyExtractor={item => item.id}
          renderItem={renderItem}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl refreshing={isLoading} onRefresh={refetch} tintColor={COLORS.primary} />
          }
          ListEmptyComponent={
            <EmptyState
              icon={<Text style={{ fontSize: 52 }}>✉️</Text>}
              title={t.inbox.empty_title}
              description={statusFilter === 'all' ? t.inbox.empty_desc : t.inbox.empty_filtered(statusFilter.replace('_', ' '))}
            />
          }
        />
      )}
    </SafeAreaView>
  );
}

function ConversationRow({
  item,
  time,
  onPress,
  theme,
}: {
  item: Conversation;
  time: string;
  onPress: () => void;
  theme: any;
}) {
  const { t } = useTranslation();
  const scale = useRef(new Animated.Value(1)).current;
  const statusColor = STATUS_COLORS[(item as any).status] ?? theme.border;

  const onPressIn = () => Animated.spring(scale, { toValue: 0.98, useNativeDriver: true, speed: 60 }).start();
  const onPressOut = () => Animated.spring(scale, { toValue: 1, useNativeDriver: true, speed: 30, bounciness: 4 }).start();

  return (
    <TouchableOpacity
      onPress={onPress}
      onPressIn={onPressIn}
      onPressOut={onPressOut}
      activeOpacity={1}>
      <Animated.View
        style={[
          styles.item,
          { backgroundColor: theme.surface, borderBottomColor: theme.border, transform: [{ scale }] },
        ]}>
        <View style={[styles.avatar, { backgroundColor: COLORS.primaryUltraLight }]}>
          <Text style={[styles.avatarText, { color: COLORS.primaryDark }]}>
            {(item.chatbot_name ?? 'C')[0].toUpperCase()}
          </Text>
        </View>

        <View style={styles.itemContent}>
          <View style={styles.itemHeader}>
            <Text style={[styles.chatbotName, { color: theme.text }]} numberOfLines={1}>
              {item.chatbot_name ?? 'Conversation'}
            </Text>
            <Text style={[styles.time, { color: theme.textMuted }]}>{time}</Text>
          </View>
          <View style={styles.itemFooter}>
            <Text style={[styles.preview, { color: theme.textSecondary }]} numberOfLines={1}>
              {item.last_message ?? t.inbox.no_messages}
            </Text>
            {(item as any).status && (item as any).status !== 'open' && (
              <View style={[styles.statusDot, { backgroundColor: statusColor }]} />
            )}
            {(item.message_count ?? 0) > 0 && (
              <View style={[styles.msgCount, { backgroundColor: COLORS.primary }]}>
                <Text style={styles.msgCountText}>{item.message_count}</Text>
              </View>
            )}
          </View>
        </View>
      </Animated.View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },

  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
    gap: SPACING.sm,
  },
  headerTitle: { ...TEXT.h3 },
  countBadge: {
    borderRadius: RADIUS.full,
    paddingVertical: 3,
    paddingHorizontal: SPACING.sm,
    minWidth: 28,
    alignItems: 'center',
  },
  countBadgeText: { fontSize: FONT_SIZE.xs, fontWeight: '700' },

  filterBar: { borderBottomWidth: 1, flexGrow: 0 },
  filterBarContent: { paddingHorizontal: SPACING.lg },
  filterTab: {
    paddingVertical: SPACING.sm,
    paddingHorizontal: SPACING.md,
    marginRight: SPACING.xs,
  },
  filterTabText: { fontSize: FONT_SIZE.sm, fontWeight: '500' },

  item: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
    gap: SPACING.md,
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: RADIUS.full,
    alignItems: 'center',
    justifyContent: 'center',
    flexShrink: 0,
  },
  avatarText: { fontSize: FONT_SIZE.lg, fontWeight: '800' },

  itemContent: { flex: 1 },
  itemHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 },
  chatbotName: { ...TEXT.bodyM, flex: 1, marginRight: SPACING.sm },
  time: { fontSize: FONT_SIZE.xs },

  itemFooter: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: SPACING.xs },
  preview: { ...TEXT.small, flex: 1 },
  statusDot: { width: 8, height: 8, borderRadius: RADIUS.full, flexShrink: 0 },
  msgCount: {
    borderRadius: RADIUS.full,
    minWidth: 20,
    height: 20,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 6,
  },
  msgCountText: { color: COLORS.white, fontSize: 11, fontWeight: '700' },
});
