/**
 * Email inbox — threaded messages, search, compose.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../themes/ThemeProvider';
import { getEmails, EmailMessage } from '../../services/api';

export default function Inbox({ navigation }: any) {
  const { theme } = useTheme();
  const [emails, setEmails] = useState<EmailMessage[]>([]);
  const [search, setSearch] = useState('');
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const params: Record<string, string> = {};
    if (search) params.search = search;
    const res = await getEmails(params);
    if (res.success && res.data) setEmails(res.data);
  }, [search]);

  useEffect(() => {
    load();
  }, [load]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await load();
    setRefreshing(false);
  }, [load]);

  const formatDate = (ts: string): string => {
    try {
      const d = new Date(ts);
      const now = new Date();
      const isToday = d.toDateString() === now.toDateString();
      if (isToday) return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
      return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    } catch {
      return '';
    }
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <View style={[styles.searchBar, { backgroundColor: theme.colors.surface }]}>
        <TextInput
          style={[styles.searchInput, { color: theme.colors.text, backgroundColor: theme.colors.inputBg }]}
          placeholder="Search emails..."
          placeholderTextColor={theme.colors.textSecondary}
          value={search}
          onChangeText={setSearch}
          onSubmitEditing={load}
          returnKeyType="search"
        />
        <TouchableOpacity
          style={[styles.composeBtn, { backgroundColor: theme.colors.primary }]}
          onPress={() => navigation.navigate('Compose')}
        >
          <Text style={styles.composeBtnText}>+</Text>
        </TouchableOpacity>
      </View>

      <FlatList
        data={emails}
        keyExtractor={(item) => String(item.id)}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        renderItem={({ item }) => (
          <TouchableOpacity
            style={[
              styles.emailRow,
              { backgroundColor: theme.colors.card, borderBottomColor: theme.colors.border },
              !item.is_read && styles.unread,
            ]}
            onPress={() => navigation.navigate('Compose', { replyTo: item.thread_id })}
          >
            <View style={styles.emailHeader}>
              <Text
                style={[
                  styles.sender,
                  { color: theme.colors.text },
                  !item.is_read && styles.unreadText,
                ]}
                numberOfLines={1}
              >
                {item.is_outbound ? `To: ${item.to_address}` : item.from_address}
              </Text>
              <Text style={[styles.date, { color: theme.colors.textSecondary }]}>
                {formatDate(item.created_at)}
              </Text>
            </View>
            <Text
              style={[
                styles.subject,
                { color: theme.colors.text },
                !item.is_read && styles.unreadText,
              ]}
              numberOfLines={1}
            >
              {item.subject || '(no subject)'}
            </Text>
            <Text style={[styles.preview, { color: theme.colors.textSecondary }]} numberOfLines={2}>
              {item.body?.replace(/<[^>]+>/g, '').substring(0, 150) || ''}
            </Text>
          </TouchableOpacity>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No emails found</Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  searchBar: { flexDirection: 'row', padding: 12, gap: 10 },
  searchInput: { flex: 1, height: 40, borderRadius: 10, paddingHorizontal: 14, fontSize: 15 },
  composeBtn: { width: 40, height: 40, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  composeBtnText: { color: '#FFF', fontSize: 24, fontWeight: '300', marginTop: -2 },
  emailRow: {
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  unread: { backgroundColor: '#F0F5FF' },
  emailHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 2,
  },
  sender: { fontSize: 14, flex: 1, marginRight: 8 },
  unreadText: { fontWeight: '700' },
  date: { fontSize: 12 },
  subject: { fontSize: 15, marginBottom: 4 },
  preview: { fontSize: 13, lineHeight: 18 },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
