import React, { useState, useCallback, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Alert,
  Modal,
  ActivityIndicator,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as SecureStore from 'expo-secure-store';
import { api } from '@/services/api';
import { useBeneficiary } from '@/contexts/BeneficiaryContext';
import { AppColors, BorderRadius, FontSizes, Spacing } from '@/constants/theme';
import type { Message, Beneficiary } from '@/types';

const API_URL = 'https://eluxnetworks.net/function/well-api/api';

export default function ChatScreen() {
  const { currentBeneficiary, setCurrentBeneficiary, getBeneficiaryContext } = useBeneficiary();
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      role: 'assistant',
      content: 'Hello! I\'m Julia, your AI assistant. How can I help you today?',
      timestamp: new Date(),
    },
  ]);
  const [input, setInput] = useState('');
  const [isSending, setIsSending] = useState(false);
  const flatListRef = useRef<FlatList>(null);

  // Beneficiary picker state
  const [showBeneficiaryPicker, setShowBeneficiaryPicker] = useState(false);
  const [beneficiaries, setBeneficiaries] = useState<Beneficiary[]>([]);
  const [loadingBeneficiaries, setLoadingBeneficiaries] = useState(false);

  // Load beneficiaries when picker opens
  const loadBeneficiaries = useCallback(async () => {
    setLoadingBeneficiaries(true);
    try {
      const response = await api.getAllBeneficiaries();
      if (response.ok && response.data) {
        setBeneficiaries(response.data);
        return response.data;
      }
      return [];
    } catch (error) {
      console.error('Failed to load beneficiaries:', error);
      return [];
    } finally {
      setLoadingBeneficiaries(false);
    }
  }, []);

  // Auto-select first beneficiary on mount if none selected
  useEffect(() => {
    const autoSelectBeneficiary = async () => {
      if (!currentBeneficiary) {
        const loaded = await loadBeneficiaries();
        if (loaded.length > 0) {
          setCurrentBeneficiary(loaded[0]);
          console.log('Auto-selected first beneficiary:', loaded[0].name);
        }
      }
    };
    autoSelectBeneficiary();
  }, []);

  const openBeneficiaryPicker = useCallback(() => {
    setShowBeneficiaryPicker(true);
    loadBeneficiaries();
  }, [loadBeneficiaries]);

  const selectBeneficiary = useCallback((beneficiary: Beneficiary) => {
    setCurrentBeneficiary(beneficiary);
    setShowBeneficiaryPicker(false);
  }, [setCurrentBeneficiary]);

  // Fetch activity data for context
  const getActivityContext = async (token: string, userName: string, deploymentId: string): Promise<string> => {
    try {
      const response = await fetch(API_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          function: 'activities_report_details',
          user_name: userName,
          token: token,
          deployment_id: deploymentId,
          filter: '0',
        }).toString(),
      });

      const data = await response.json();
      if (!data.chart_data || data.chart_data.length === 0) return '';

      const weeklyData = data.chart_data.find((d: any) => d.name === 'Weekly');
      if (!weeklyData) return '';

      const lines: string[] = [];
      if (data.alert_text) lines.push(`Alert status: ${data.alert_text}`);

      const todayStats: string[] = [];
      for (const room of weeklyData.rooms) {
        const todayData = room.data[room.data.length - 1];
        if (todayData && todayData.hours > 0) {
          todayStats.push(`${room.name}: ${todayData.hours.toFixed(1)} hours (${todayData.events} events)`);
        }
      }
      if (todayStats.length > 0) lines.push(`Today's activity: ${todayStats.join(', ')}`);

      const weeklyStats: string[] = [];
      for (const room of weeklyData.rooms) {
        const totalHours = room.data.reduce((sum: number, d: any) => sum + d.hours, 0);
        if (totalHours > 0) {
          weeklyStats.push(`${room.name}: ${totalHours.toFixed(1)} hours total this week`);
        }
      }
      if (weeklyStats.length > 0) lines.push(`Weekly summary: ${weeklyStats.join(', ')}`);

      return lines.join('. ');
    } catch (error) {
      console.log('Failed to fetch activity context:', error);
      return '';
    }
  };

  // Fetch dashboard data as fallback context
  const getDashboardContext = async (token: string, userName: string, deploymentId: string): Promise<string> => {
    try {
      const today = new Date().toISOString().split('T')[0];

      const response = await fetch(API_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          function: 'dashboard_single',
          user_name: userName,
          token: token,
          deployment_id: deploymentId,
          date: today,
        }).toString(),
      });

      const data = await response.json();
      if (!data.result_list || data.result_list.length === 0) return '';

      const info = data.result_list[0];
      const lines: string[] = [];

      if (info.wellness_descriptor) lines.push(`Current wellness: ${info.wellness_descriptor}`);
      if (info.wellness_score_percent) lines.push(`Wellness score: ${info.wellness_score_percent}%`);
      if (info.last_location) lines.push(`Last seen in: ${info.last_location}`);
      if (info.last_detected_time) lines.push(`Last activity: ${info.last_detected_time}`);
      if (info.sleep_hours) lines.push(`Sleep hours: ${info.sleep_hours}`);
      if (info.temperature) lines.push(`Temperature: ${info.temperature}${info.units === 'F' ? '°F' : '°C'}`);

      return lines.join('. ');
    } catch (error) {
      console.log('Failed to fetch dashboard context:', error);
      return '';
    }
  };

  // Send message with full context
  const sendWithContext = async (question: string): Promise<string> => {
    const token = await SecureStore.getItemAsync('accessToken');
    const userName = await SecureStore.getItemAsync('userName');

    if (!token || !userName) throw new Error('Please log in');
    if (!currentBeneficiary?.id) throw new Error('Please select a beneficiary');

    const beneficiaryName = currentBeneficiary.name || 'the patient';
    const deploymentId = currentBeneficiary.id.toString();

    // Get activity context (primary source)
    let activityContext = await getActivityContext(token, userName, deploymentId);

    // If activity context is empty, try dashboard context as fallback
    if (!activityContext) {
      activityContext = await getDashboardContext(token, userName, deploymentId);
    }

    // Build the question with embedded context
    let enhancedQuestion: string;
    if (activityContext) {
      enhancedQuestion = `You are a caring assistant helping monitor ${beneficiaryName}'s wellbeing.

Here is the current data about ${beneficiaryName}:
${activityContext}

Based on this data, please answer the following question: ${question}`;
    } else {
      enhancedQuestion = `You are a caring assistant helping monitor ${beneficiaryName}'s wellbeing. Please answer: ${question}`;
    }

    // Call API
    const requestBody = new URLSearchParams({
      function: 'voice_ask',
      clientId: '001',
      user_name: userName,
      token: token,
      question: enhancedQuestion,
      deployment_id: deploymentId,
      context: activityContext || '',
    }).toString();

    const response = await fetch(API_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: requestBody,
    });

    const data = await response.json();

    if (data.ok && data.response?.body) {
      return data.response.body;
    } else if (data.status === '401 Unauthorized') {
      throw new Error('Session expired. Please log in again.');
    } else {
      throw new Error('Could not get response');
    }
  };

  const handleSend = useCallback(async () => {
    const trimmedInput = input.trim();
    if (!trimmedInput || isSending) return;

    // Require beneficiary to be selected
    if (!currentBeneficiary?.id) {
      Alert.alert(
        'Select Beneficiary',
        'Please select a beneficiary using the icon in the top right corner.',
        [{ text: 'OK' }]
      );
      return;
    }

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: trimmedInput,
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setInput('');
    setIsSending(true);

    try {
      const aiResponse = await sendWithContext(trimmedInput);

      const assistantMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: aiResponse,
        timestamp: new Date(),
      };
      setMessages((prev) => [...prev, assistantMessage]);
    } catch (error) {
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}. Please try again.`,
        timestamp: new Date(),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setIsSending(false);
    }
  }, [input, isSending, currentBeneficiary]);

  const renderMessage = ({ item }: { item: Message }) => {
    const isUser = item.role === 'user';

    return (
      <View
        style={[
          styles.messageContainer,
          isUser ? styles.userMessageContainer : styles.assistantMessageContainer,
        ]}
      >
        {!isUser && (
          <View style={styles.avatarContainer}>
            <Text style={styles.avatarText}>J</Text>
          </View>
        )}
        <View
          style={[
            styles.messageBubble,
            isUser ? styles.userBubble : styles.assistantBubble,
          ]}
        >
          <Text
            style={[
              styles.messageText,
              isUser ? styles.userMessageText : styles.assistantMessageText,
            ]}
          >
            {item.content}
          </Text>
          <Text style={[styles.timestamp, isUser && styles.userTimestamp]}>
            {item.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
          </Text>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerInfo}>
          <View style={styles.headerAvatar}>
            <Text style={styles.headerAvatarText}>J</Text>
          </View>
          <View>
            <Text style={styles.headerTitle}>Julia AI</Text>
            <Text style={styles.headerSubtitle}>
              {isSending
                ? 'Typing...'
                : currentBeneficiary
                  ? `About ${currentBeneficiary.name}`
                  : 'Online'}
            </Text>
          </View>
        </View>
        <TouchableOpacity style={styles.headerButton} onPress={openBeneficiaryPicker}>
          <Ionicons name="people-outline" size={24} color={AppColors.primary} />
        </TouchableOpacity>
      </View>

      {/* Beneficiary Picker Modal */}
      <Modal
        visible={showBeneficiaryPicker}
        transparent
        animationType="slide"
        onRequestClose={() => setShowBeneficiaryPicker(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Select Beneficiary</Text>
              <TouchableOpacity onPress={() => setShowBeneficiaryPicker(false)}>
                <Ionicons name="close" size={24} color={AppColors.textPrimary} />
              </TouchableOpacity>
            </View>

            {loadingBeneficiaries ? (
              <View style={styles.modalLoading}>
                <ActivityIndicator size="large" color={AppColors.primary} />
                <Text style={styles.loadingText}>Loading beneficiaries...</Text>
              </View>
            ) : beneficiaries.length === 0 ? (
              <View style={styles.modalEmpty}>
                <Text style={styles.emptyText}>No beneficiaries found</Text>
              </View>
            ) : (
              <FlatList
                data={beneficiaries}
                keyExtractor={(item) => item.id.toString()}
                renderItem={({ item }) => (
                  <TouchableOpacity
                    style={[
                      styles.beneficiaryItem,
                      currentBeneficiary?.id === item.id && styles.beneficiaryItemSelected,
                    ]}
                    onPress={() => selectBeneficiary(item)}
                  >
                    <View style={styles.beneficiaryAvatar}>
                      <Text style={styles.beneficiaryAvatarText}>
                        {item.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                      </Text>
                    </View>
                    <View style={styles.beneficiaryInfo}>
                      <Text style={styles.beneficiaryName}>{item.name}</Text>
                      {item.email && (
                        <Text style={styles.beneficiaryEmail}>{item.email}</Text>
                      )}
                    </View>
                    {currentBeneficiary?.id === item.id && (
                      <Ionicons name="checkmark-circle" size={24} color={AppColors.success} />
                    )}
                  </TouchableOpacity>
                )}
                style={styles.beneficiaryList}
              />
            )}
          </View>
        </View>
      </Modal>

      {/* Messages */}
      <KeyboardAvoidingView
        style={styles.chatContainer}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
      >
        <FlatList
          ref={flatListRef}
          data={messages}
          keyExtractor={(item) => item.id}
          renderItem={renderMessage}
          contentContainerStyle={styles.messagesList}
          showsVerticalScrollIndicator={false}
          onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: true })}
        />

        {/* Input */}
        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            placeholder="Type a message..."
            placeholderTextColor={AppColors.textMuted}
            value={input}
            onChangeText={setInput}
            multiline
            maxLength={1000}
            editable={!isSending}
            onSubmitEditing={handleSend}
          />
          <TouchableOpacity
            style={[styles.sendButton, (!input.trim() || isSending) && styles.sendButtonDisabled]}
            onPress={handleSend}
            disabled={!input.trim() || isSending}
          >
            <Ionicons
              name={isSending ? 'hourglass' : 'send'}
              size={20}
              color={input.trim() && !isSending ? AppColors.white : AppColors.textMuted}
            />
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.surface,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    backgroundColor: AppColors.background,
    borderBottomWidth: 1,
    borderBottomColor: AppColors.border,
  },
  headerInfo: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerAvatar: {
    width: 40,
    height: 40,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.success,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.sm,
  },
  headerAvatarText: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.white,
  },
  headerTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
  },
  headerSubtitle: {
    fontSize: FontSizes.sm,
    color: AppColors.success,
  },
  headerButton: {
    padding: Spacing.xs,
  },
  chatContainer: {
    flex: 1,
  },
  messagesList: {
    padding: Spacing.md,
    paddingBottom: Spacing.lg,
  },
  messageContainer: {
    flexDirection: 'row',
    marginBottom: Spacing.md,
    alignItems: 'flex-end',
  },
  userMessageContainer: {
    justifyContent: 'flex-end',
  },
  assistantMessageContainer: {
    justifyContent: 'flex-start',
  },
  avatarContainer: {
    width: 32,
    height: 32,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.success,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.xs,
  },
  avatarText: {
    fontSize: FontSizes.sm,
    fontWeight: '600',
    color: AppColors.white,
  },
  messageBubble: {
    maxWidth: '75%',
    padding: Spacing.sm + 4,
    borderRadius: BorderRadius.lg,
  },
  userBubble: {
    backgroundColor: AppColors.primary,
    borderBottomRightRadius: BorderRadius.sm,
  },
  assistantBubble: {
    backgroundColor: AppColors.background,
    borderBottomLeftRadius: BorderRadius.sm,
  },
  messageText: {
    fontSize: FontSizes.base,
    lineHeight: 22,
  },
  userMessageText: {
    color: AppColors.white,
  },
  assistantMessageText: {
    color: AppColors.textPrimary,
  },
  timestamp: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
    marginTop: Spacing.xs,
    alignSelf: 'flex-end',
  },
  userTimestamp: {
    color: 'rgba(255,255,255,0.7)',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    padding: Spacing.md,
    backgroundColor: AppColors.background,
    borderTopWidth: 1,
    borderTopColor: AppColors.border,
  },
  input: {
    flex: 1,
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.xl,
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    fontSize: FontSizes.base,
    color: AppColors.textPrimary,
    maxHeight: 100,
    marginRight: Spacing.sm,
  },
  sendButton: {
    width: 44,
    height: 44,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  sendButtonDisabled: {
    backgroundColor: AppColors.surface,
  },
  // Modal styles
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: AppColors.background,
    borderTopLeftRadius: BorderRadius.xl,
    borderTopRightRadius: BorderRadius.xl,
    maxHeight: '70%',
    paddingBottom: Spacing.xl,
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: Spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: AppColors.border,
  },
  modalTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
  },
  modalLoading: {
    padding: Spacing.xl,
    alignItems: 'center',
  },
  loadingText: {
    marginTop: Spacing.md,
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
  },
  modalEmpty: {
    padding: Spacing.xl,
    alignItems: 'center',
  },
  emptyText: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
  },
  beneficiaryList: {
    paddingHorizontal: Spacing.md,
  },
  beneficiaryItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: Spacing.md,
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.md,
    marginTop: Spacing.sm,
  },
  beneficiaryItemSelected: {
    backgroundColor: AppColors.primaryLight || '#E3F2FD',
    borderWidth: 1,
    borderColor: AppColors.primary,
  },
  beneficiaryAvatar: {
    width: 44,
    height: 44,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.md,
  },
  beneficiaryAvatarText: {
    fontSize: FontSizes.base,
    fontWeight: '600',
    color: AppColors.white,
  },
  beneficiaryInfo: {
    flex: 1,
  },
  beneficiaryName: {
    fontSize: FontSizes.base,
    fontWeight: '500',
    color: AppColors.textPrimary,
  },
  beneficiaryEmail: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
    marginTop: 2,
  },
});
