import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, FlatList, TextInput, TouchableOpacity, Alert, RefreshControl, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLocalSearchParams } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useAuth } from '@/context/AuthContext';
import { InquiryAPI } from '@/services/api';
import { Card } from '@/components/ui/Card';
import { EmptyState } from '@/components/ui/EmptyState';
import { ScreenHeader } from '@/components/ui/ScreenHeader';
import { Colors, FontSize, Spacing, Radius } from '@/constants/theme';

export default function InquiriesScreen() {
  const { user } = useAuth();
  const params = useLocalSearchParams<{ boarding_house_id?: string; landlord_id?: string }>();
  const [inquiries, setInquiries] = useState<any[]>([]);
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    try {
      const d = await InquiryAPI.getByTenant(user!.id);
      setInquiries(d.data ?? []);
    } catch (_) {}
    setLoading(false);
    setRefreshing(false);
  }, [user]);

  useEffect(() => { load(); }, [load]);

  async function handleSend() {
    if (!message.trim()) return;
    if (!params.boarding_house_id) {
      Alert.alert('Select a boarding house', 'Go to a boarding house detail page to send an inquiry.');
      return;
    }
    setSending(true);
    try {
      await InquiryAPI.create({
        tenant_id: user!.id,
        landlord_id: params.landlord_id,
        boarding_house_id: params.boarding_house_id,
        message: message.trim(),
      });
      setMessage('');
      load();
    } catch (err: any) {
      Alert.alert('Error', err.message);
    } finally {
      setSending(false);
    }
  }

  if (loading) return <View style={styles.center}><ActivityIndicator color={Colors.primary} size="large" /></View>;

  return (
    <SafeAreaView style={styles.safe} edges={['top']}>
      <ScreenHeader title="Inquiries" subtitle="Messages with landlords" showMenu />
      <FlatList
        data={inquiries}
        keyExtractor={item => String(item.id)}
        contentContainerStyle={styles.content}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); load(); }} />}
        ListEmptyComponent={<EmptyState icon="chatbubble-outline" title="No inquiries yet" message="Send a message to a landlord from a boarding house detail page." />}
        renderItem={({ item }) => (
          <Card style={styles.card}>
            <Text style={styles.bhName}>{item.boarding_house_name}</Text>
            <View style={styles.messageBox}>
              <Ionicons name="person-circle-outline" size={20} color={Colors.primary} />
              <Text style={styles.messageText}>{item.message}</Text>
            </View>
            <Text style={styles.timestamp}>{item.created_at?.split('T')[0]}</Text>
            {item.reply && (
              <View style={styles.replyBox}>
                <Ionicons name="chatbubble-ellipses-outline" size={16} color={Colors.success} />
                <Text style={styles.replyText}>{item.reply}</Text>
              </View>
            )}
          </Card>
        )}
      />
      {/* Compose */}
      {params.boarding_house_id && (
        <View style={styles.compose}>
          <TextInput
            style={styles.composeInput}
            placeholder="Type your message..."
            placeholderTextColor={Colors.textLight}
            value={message}
            onChangeText={setMessage}
            multiline
          />
          <TouchableOpacity onPress={handleSend} disabled={sending || !message.trim()} style={styles.sendBtn}>
            <Ionicons name="send" size={20} color={Colors.textInverse} />
          </TouchableOpacity>
        </View>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: Colors.background },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  content: { padding: Spacing.md, gap: Spacing.sm, paddingBottom: Spacing.xl },
  card: { padding: Spacing.md, gap: Spacing.sm },
  bhName: { fontSize: FontSize.sm, fontWeight: '700', color: Colors.primary },
  messageBox: { flexDirection: 'row', gap: Spacing.sm, alignItems: 'flex-start' },
  messageText: { flex: 1, fontSize: FontSize.md, color: Colors.text, lineHeight: 20 },
  timestamp: { fontSize: FontSize.xs, color: Colors.textLight },
  replyBox: { flexDirection: 'row', gap: Spacing.sm, backgroundColor: '#F0FDF4', borderRadius: Radius.sm, padding: Spacing.sm, alignItems: 'flex-start' },
  replyText: { flex: 1, fontSize: FontSize.sm, color: Colors.text, lineHeight: 18 },
  compose: {
    flexDirection: 'row', alignItems: 'flex-end', gap: Spacing.sm,
    padding: Spacing.md, backgroundColor: Colors.surface,
    borderTopWidth: 1, borderTopColor: Colors.border,
  },
  composeInput: {
    flex: 1, backgroundColor: Colors.background, borderRadius: Radius.lg,
    paddingHorizontal: Spacing.md, paddingVertical: Spacing.sm,
    fontSize: FontSize.md, color: Colors.text, maxHeight: 100,
  },
  sendBtn: {
    width: 44, height: 44, borderRadius: 22,
    backgroundColor: Colors.primary, alignItems: 'center', justifyContent: 'center',
  },
});
