import React, { useState, useRef } from 'react'
import {
  View, Text, TextInput, TouchableOpacity,
  FlatList, StyleSheet, KeyboardAvoidingView, Platform,
  ActivityIndicator,
} from 'react-native'
import { apiFetch } from '../lib/api'

interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  ts: number
}

export default function AiChatScreen() {
  const [messages, setMessages] = useState<Message[]>([
    { id: '0', role: 'assistant', content: 'Hello! How can I help you today?', ts: Date.now() },
  ])
  const [sessionId, setSessionId] = useState<string | undefined>(undefined)
  const [input, setInput]         = useState('')
  const [loading, setLoading]     = useState(false)
  const listRef                   = useRef<FlatList>(null)

  async function send() {
    const text = input.trim()
    if (!text || loading) return
    setInput('')

    const userMsg: Message = { id: Date.now().toString(), role: 'user', content: text, ts: Date.now() }
    setMessages(m => [...m, userMsg])
    setLoading(true)

    try {
      const data = await apiFetch('/agent/chat', {
        method: 'POST',
        body: JSON.stringify({ sessionId, message: text }),
      })

      if (data.sessionId && !sessionId) setSessionId(data.sessionId)

      setMessages(m => [...m, {
        id:      (Date.now() + 1).toString(),
        role:    'assistant',
        content: data.response ?? '(No response)',
        ts:      Date.now(),
      }])
    } catch (e: any) {
      setMessages(m => [...m, { id: (Date.now() + 1).toString(), role: 'assistant', content: `Error: ${e.message}`, ts: Date.now() }])
    } finally {
      setLoading(false)
      setTimeout(() => listRef.current?.scrollToEnd({ animated: true }), 100)
    }
  }

  const renderMessage = ({ item }: { item: Message }) => {
    const isUser = item.role === 'user'
    return (
      <View style={[styles.bubble, isUser ? styles.userBubble : styles.assistantBubble]}>
        <Text style={[styles.bubbleText, isUser ? styles.userText : styles.assistantText]}>{item.content}</Text>
      </View>
    )
  }

  return (
    <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.container} keyboardVerticalOffset={90}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>AI Assistant</Text>
        <Text style={styles.headerSub}>Prompt Analyst · Soi96 Legal</Text>
      </View>

      <FlatList
        ref={listRef}
        data={messages}
        keyExtractor={m => m.id}
        renderItem={renderMessage}
        style={styles.list}
        contentContainerStyle={{ padding: 16, gap: 10 }}
        onContentSizeChange={() => listRef.current?.scrollToEnd()}
      />

      {loading && (
        <View style={styles.typingIndicator}>
          <ActivityIndicator size='small' color='#0D9394' />
          <Text style={styles.typingText}>Thinking…</Text>
        </View>
      )}

      <View style={styles.inputRow}>
        <TextInput
          style={styles.input}
          value={input}
          onChangeText={setInput}
          placeholder='Ask about immigration law, billing, matters…'
          placeholderTextColor='#9CA3AF'
          multiline
          maxLength={2000}
          onSubmitEditing={send}
          blurOnSubmit={false}
        />
        <TouchableOpacity style={[styles.sendBtn, (!input.trim() || loading) && styles.sendBtnDisabled]} onPress={send} disabled={!input.trim() || loading}>
          <Text style={styles.sendIcon}>↑</Text>
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  )
}

const styles = StyleSheet.create({
  container:        { flex: 1, backgroundColor: '#F9FAFB' },
  header:           { paddingHorizontal: 16, paddingTop: 8, paddingBottom: 12, backgroundColor: '#fff', borderBottomWidth: 1, borderBottomColor: '#E5E7EB' },
  headerTitle:      { fontSize: 17, fontWeight: '700', color: '#0D9394' },
  headerSub:        { fontSize: 11, color: '#9CA3AF', marginTop: 1 },
  list:             { flex: 1 },
  bubble:           { maxWidth: '85%', borderRadius: 16, padding: 12 },
  userBubble:       { alignSelf: 'flex-end', backgroundColor: '#0D9394', borderBottomRightRadius: 4 },
  assistantBubble:  { alignSelf: 'flex-start', backgroundColor: '#fff', borderBottomLeftRadius: 4, shadowColor: '#000', shadowOpacity: 0.05, shadowRadius: 4, elevation: 1 },
  bubbleText:       { fontSize: 14, lineHeight: 20 },
  userText:         { color: '#fff' },
  assistantText:    { color: '#1A1A2E' },
  typingIndicator:  { flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 16, paddingBottom: 4 },
  typingText:       { fontSize: 12, color: '#9CA3AF' },
  inputRow:         { flexDirection: 'row', padding: 12, gap: 10, backgroundColor: '#fff', borderTopWidth: 1, borderTopColor: '#E5E7EB', alignItems: 'flex-end' },
  input:            { flex: 1, backgroundColor: '#F3F4F6', borderRadius: 20, paddingHorizontal: 14, paddingVertical: 10, fontSize: 14, color: '#1A1A2E', maxHeight: 120 },
  sendBtn:          { width: 40, height: 40, borderRadius: 20, backgroundColor: '#0D9394', alignItems: 'center', justifyContent: 'center' },
  sendBtnDisabled:  { backgroundColor: '#D1D5DB' },
  sendIcon:         { color: '#fff', fontWeight: '700', fontSize: 18, lineHeight: 22 },
})
