import { useRef, useState } from 'react';
import { View, Text, StyleSheet, Pressable, TextInput, ScrollView, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { colors, spacing, radii, typography } from '../../../theme';
import { DieticianChatTurn, sendDieticianChatMessage } from '../../../api/dieticianReport';

type Props = {
  date: string;
  initialMessages: DieticianChatTurn[];
  onClose: () => void;
};

const SUGGESTIONS = ['Pourquoi ce conseil ?', 'Ajuste mon dîner de demain', 'Comment améliorer mon hydratation ?'];

type DisplayMessage = { from: 'bot' | 'user'; text: string };

const WELCOME: DisplayMessage = {
  from: 'bot',
  text: "Salut ! J'ai regardé ton bilan de cette journée — pose-moi tes questions, ou demande-moi d'ajuster quelque chose.",
};

// Chat "Demander à ClemAI" (maquette Claude Design "Bilan de journée ClemAI") : affiché en
// ligne sous le bilan, pas en modale, pour que la conversation reste visible avec le reste
// de la page comme un fil de discussion. Persisté côté serveur par bilan
// (`DieticianReportService::askAboutReport()`) — `initialMessages` vient de l'historique
// déjà enregistré (`GET /dietician-report/latest`) ; l'écran (`DieticianReportScreen.tsx`)
// remonte ce composant à chaque changement de jour affiché (prop React `key`), donc pas
// besoin ici de resynchroniser `initialMessages` après le montage.
export function DieticianChatThread({ date, initialMessages, onClose }: Props) {
  const [messages, setMessages] = useState<DisplayMessage[]>(
    initialMessages.length > 0
      ? initialMessages.map((m) => ({ from: m.role === 'user' ? 'user' : 'bot', text: m.text }))
      : [WELCOME],
  );
  const [draft, setDraft] = useState('');
  const [sending, setSending] = useState(false);
  const scrollRef = useRef<ScrollView>(null);

  function scrollToBottom() {
    requestAnimationFrame(() => scrollRef.current?.scrollToEnd({ animated: true }));
  }

  async function send(text: string) {
    const question = text.trim();
    if (question === '' || sending) return;

    setMessages((prev) => [...prev, { from: 'user', text: question }]);
    setDraft('');
    setSending(true);
    scrollToBottom();

    try {
      const { reply } = await sendDieticianChatMessage(date, question);
      setMessages((prev) => [...prev, { from: 'bot', text: reply }]);
    } catch {
      setMessages((prev) => [...prev, { from: 'bot', text: "Désolé, je n'ai pas réussi à répondre — réessaie dans un instant." }]);
    } finally {
      setSending(false);
      scrollToBottom();
    }
  }

  return (
    <View style={styles.card}>
      <View style={styles.header}>
        <Ionicons name="chatbubble-ellipses-outline" size={18} color={colors.primary} />
        <Text style={styles.title}>Demander à ClemAI</Text>
        <Pressable onPress={onClose} hitSlop={10}>
          <Ionicons name="close" size={20} color={colors.textMuted} />
        </Pressable>
      </View>

      <ScrollView
        ref={scrollRef}
        style={styles.messages}
        contentContainerStyle={styles.messagesContent}
        onContentSizeChange={scrollToBottom}
        nestedScrollEnabled
      >
        {messages.map((message, index) => (
          <View key={index} style={[styles.bubbleRow, message.from === 'user' ? styles.bubbleRowUser : styles.bubbleRowBot]}>
            <View style={[styles.bubble, message.from === 'user' ? styles.bubbleUser : styles.bubbleBot]}>
              <Text style={message.from === 'user' ? styles.bubbleTextUser : styles.bubbleTextBot}>{message.text}</Text>
            </View>
          </View>
        ))}
        {sending && (
          <View style={[styles.bubbleRow, styles.bubbleRowBot]}>
            <View style={[styles.bubble, styles.bubbleBot]}>
              <ActivityIndicator size="small" color={colors.textMuted} />
            </View>
          </View>
        )}
      </ScrollView>

      <View style={styles.suggestions}>
        {SUGGESTIONS.map((suggestion) => (
          <Pressable key={suggestion} style={styles.suggestionChip} onPress={() => send(suggestion)} disabled={sending}>
            <Text style={styles.suggestionText}>{suggestion}</Text>
          </Pressable>
        ))}
      </View>

      <View style={styles.inputRow}>
        <TextInput
          style={styles.input}
          value={draft}
          onChangeText={setDraft}
          placeholder="Pose une question à ClemAI…"
          placeholderTextColor={colors.textMuted}
          onSubmitEditing={() => send(draft)}
          editable={!sending}
        />
        <Pressable style={[styles.sendButton, sending && styles.sendButtonDisabled]} onPress={() => send(draft)} disabled={sending}>
          <Ionicons name="send" size={18} color="#fff" />
        </Pressable>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  // Pas de boîte blanche englobante : le fil doit occuper toute la largeur du fond gris
  // de l'écran (même marge que le reste de `DieticianReportScreen.tsx`), comme une vraie
  // conversation posée sur la page plutôt qu'encartée — `bubbleBot` ci-dessous est donc en
  // blanc (`colors.card`), pas `colors.surface` (quasi identique au gris de fond), pour
  // rester lisible sans ce fond de carte.
  card: { gap: spacing.sm },
  header: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  title: { ...typography.body, fontWeight: '800', fontSize: 16, color: colors.text, flex: 1 },
  messages: { maxHeight: 360 },
  messagesContent: { gap: spacing.sm, paddingVertical: spacing.xs },
  bubbleRow: { flexDirection: 'row' },
  // Utilisateur à GAUCHE, ClemIA à DROITE (même convention que ClemIAScreen.tsx —
  // demande explicite utilisateur, inversée par rapport au chat habituel).
  bubbleRowUser: { justifyContent: 'flex-start' },
  bubbleRowBot: { justifyContent: 'flex-end' },
  bubble: { maxWidth: '82%', paddingVertical: 10, paddingHorizontal: 14, borderRadius: radii.lg },
  bubbleUser: { backgroundColor: colors.primary },
  bubbleBot: { backgroundColor: colors.card },
  bubbleTextUser: { ...typography.body, color: '#fff', lineHeight: 20 },
  bubbleTextBot: { ...typography.body, color: colors.text, lineHeight: 20 },
  suggestions: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
  suggestionChip: {
    paddingVertical: 7,
    paddingHorizontal: 12,
    borderRadius: radii.pill,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.card,
  },
  suggestionText: { ...typography.caption, color: colors.text },
  inputRow: { flexDirection: 'row', gap: spacing.sm, alignItems: 'center' },
  input: {
    flex: 1,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingHorizontal: spacing.md,
    paddingVertical: 12,
    ...typography.body,
    fontSize: 14.5,
    color: colors.text,
    backgroundColor: colors.card,
  },
  sendButton: {
    width: 44,
    height: 44,
    borderRadius: radii.md,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  sendButtonDisabled: { opacity: 0.5 },
});
