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 { 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 { Button } from '@/components/ui/Button';
import { Colors, FontSize, Spacing, Radius } from '@/constants/theme';

export default function LandlordInquiriesScreen() {
  const { user } = useAuth();
  const [inquiries, setInquiries] = useState<any[]>([]);
  const [replyText, setReplyText] = useState<Record<number, string>>({});
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    try {
      const d = await InquiryAPI.getByLandlord(user!.id);
      setInquiries(d.data ?? []);
    } catch (_) {}
    setLoading(false);
    setRefreshing(false);
  }, [user]);

  useEffect(() => { load(); }, [load]);

  async function handleReply(id: number) {
    const reply = replyText[id]?.trim();
    if (!reply) return;
    try {
      await InquiryAPI.reply(id, reply);
      setReplyText(prev => ({ ...prev, [id]: '' }));
      load();
    } catch (err: any) {
      Alert.alert('Error', err.message);
    }
  }

  if (loading) return <View style={styles.center}><ActivityIndicator color={Colors.primary} size="large" /></View>;

  return (
    <SafeAreaView style={styles.safe} edges={['top']}>
      <ScreenHeader title="Inquiries" showBack subtitle={`${inquiries.length} messages`} />
      <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" />}
        renderItem={({ item }) => (
          <Card style={styles.card}>
            <View style={styles.cardHeader}>
              <View style={styles.avatar}>
                <Text style={styles.avatarText}>{item.tenant_name?.charAt(0)}</Text>
              </View>
              <View style={styles.headerInfo}>
                <Text style={styles.tenantName}>{item.tenant_name}</Text>
                <Text style={styles.bhName}>{item.boarding_house_name}</Text>
                <Text style={styles.timestamp}>{item.created_at?.split('T')[0]}</Text>
              </View>
            </View>
            <View style={styles.messageBox}>
              <Text style={styles.messageText}>{item.message}</Text>
            </View>
            {item.reply ? (
              <View style={styles.replyBox}>
                <Ionicons name="checkmark-circle" size={14} color={Colors.success} />
                <Text style={styles.replyText}>{item.reply}</Text>
              </View>
            ) : (
              <View style={styles.replyInput}>
                <TextInput
                  style={styles.input}
                  placeholder="Type your reply..."
                  placeholderTextColor={Colors.textLight}
                  value={replyText[item.id] ?? ''}
                  onChangeText={text => setReplyText(prev => ({ ...prev, [item.id]: text }))}
                  multiline
                />
                <Button title="Reply" size="sm" onPress={() => handleReply(item.id)} disabled={!replyText[item.id]?.trim()} />
              </View>
            )}
          </Card>
        )}
      />
    </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 },
  cardHeader: { flexDirection: 'row', gap: Spacing.md, alignItems: 'flex-start' },
  avatar: { width: 40, height: 40, borderRadius: 20, backgroundColor: Colors.primary, alignItems: 'center', justifyContent: 'center' },
  avatarText: { fontSize: FontSize.md, fontWeight: '700', color: Colors.textInverse },
  headerInfo: { flex: 1 },
  tenantName: { fontSize: FontSize.md, fontWeight: '700', color: Colors.text },
  bhName: { fontSize: FontSize.sm, color: Colors.primary },
  timestamp: { fontSize: FontSize.xs, color: Colors.textLight },
  messageBox: { backgroundColor: Colors.background, borderRadius: Radius.sm, padding: Spacing.sm },
  messageText: { fontSize: FontSize.md, color: Colors.text, lineHeight: 20 },
  replyBox: { flexDirection: 'row', gap: Spacing.sm, backgroundColor: '#F0FDF4', borderRadius: Radius.sm, padding: Spacing.sm },
  replyText: { flex: 1, fontSize: FontSize.sm, color: Colors.text },
  replyInput: { gap: Spacing.sm },
  input: {
    backgroundColor: Colors.background, borderRadius: Radius.md,
    padding: Spacing.sm, fontSize: FontSize.md, color: Colors.text,
    borderWidth: 1, borderColor: Colors.border, minHeight: 60,
  },
});
