import React, { useState, useRef } from 'react';
import {
  View,
  StyleSheet,
  ScrollView,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radii, shadows } from '../../theme/tokens';
import { SafeScreen } from '../../components/layout/SafeScreen';
import { Header } from '../../components/layout/Header';
import { H3, Body, BodyMedium, Caption, Card } from '../../components/ui';
import { t } from '../../i18n';
import { chatWithGemini, SYSTEM_PROMPTS } from '../../services/gemini';
import type { GeminiMessage } from '../../services/gemini';

const AID_CATEGORIES = [
  { icon: 'people-outline' as const, key: 'family', color: colors.primary[500] },
  { icon: 'home-outline' as const, key: 'housing', color: colors.secondary[500] },
  { icon: 'briefcase-outline' as const, key: 'employment', color: colors.brand.green },
  { icon: 'school-outline' as const, key: 'newcomers', color: colors.accent[500] },
];

export function AidsScreen({ navigation }: any) {
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [chatMode, setChatMode] = useState(false);
  const [messages, setMessages] = useState<{ id: string; role: 'user' | 'model'; text: string }[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const scrollRef = useRef<ScrollView>(null);

  const startChat = (categoryKey: string) => {
    setSelectedCategory(categoryKey);
    setChatMode(true);
    const welcomeText = t(`aids.${categoryKey}Welcome`);
    setMessages([{ id: '0', role: 'model', text: welcomeText }]);
  };

  const askQuestion = async () => {
    if (!input.trim() || loading) return;

    const userMsg = { id: Date.now().toString(), role: 'user' as const, text: input.trim() };
    setMessages((prev) => [...prev, userMsg]);
    setInput('');
    setLoading(true);

    try {
      const history: GeminiMessage[] = messages
        .filter((m) => m.id !== '0')
        .map((m) => ({ role: m.role, parts: [{ text: m.text }] }));
      history.push({ role: 'user', parts: [{ text: userMsg.text }] });

      const response = await chatWithGemini(history, SYSTEM_PROMPTS.aids);
      setMessages((prev) => [...prev, { id: (Date.now() + 1).toString(), role: 'model', text: response }]);
    } catch {
      setMessages((prev) => [...prev, { id: (Date.now() + 1).toString(), role: 'model', text: t('aids.error') }]);
    } finally {
      setLoading(false);
      setTimeout(() => scrollRef.current?.scrollToEnd({ animated: true }), 100);
    }
  };

  if (chatMode) {
    return (
      <SafeScreen backgroundColor={colors.background}>
        <Header
          title={selectedCategory ? t(`aids.${selectedCategory}`) : t('plus.aids')}
          onBack={() => { setChatMode(false); setMessages([]); }}
        />
        <KeyboardAvoidingView
          style={styles.flex}
          behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        >
          <ScrollView
            ref={scrollRef}
            style={styles.flex}
            contentContainerStyle={styles.chatContent}
            showsVerticalScrollIndicator={false}
            onContentSizeChange={() => scrollRef.current?.scrollToEnd({ animated: true })}
          >
            {messages.map((msg) => (
              <View
                key={msg.id}
                style={[
                  styles.msgBubble,
                  msg.role === 'user' ? styles.userBubble : styles.aiBubble,
                ]}
              >
                <View
                  style={[
                    styles.bubbleContent,
                    msg.role === 'user' ? styles.userContent : styles.aiContent,
                  ]}
                >
                  <Body style={msg.role === 'user' ? styles.userText : styles.aiText}>
                    {msg.text}
                  </Body>
                </View>
              </View>
            ))}
            {loading && (
              <View style={[styles.msgBubble, styles.aiBubble]}>
                <View style={[styles.bubbleContent, styles.aiContent]}>
                  <ActivityIndicator size="small" color={colors.primary[500]} />
                </View>
              </View>
            )}
          </ScrollView>

          <View style={styles.inputBar}>
            <TextInput
              style={styles.textInput}
              value={input}
              onChangeText={setInput}
              placeholder={t('aids.askPlaceholder')}
              placeholderTextColor={colors.neutral[400]}
              multiline
              maxLength={500}
            />
            <TouchableOpacity
              style={[styles.sendBtn, (!input.trim() || loading) && styles.sendBtnDisabled]}
              onPress={askQuestion}
              disabled={!input.trim() || loading}
            >
              <Ionicons name="send" size={20} color={input.trim() && !loading ? '#FFFFFF' : colors.neutral[400]} />
            </TouchableOpacity>
          </View>
        </KeyboardAvoidingView>
      </SafeScreen>
    );
  }

  return (
    <SafeScreen backgroundColor={colors.background}>
      <Header title={t('plus.aids')} onBack={() => navigation.goBack()} />
      <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.scrollContent}>
        <Body style={styles.intro} color={colors.neutral[500]}>
          {t('aids.intro')}
        </Body>

        {/* Category cards */}
        <View style={styles.grid}>
          {AID_CATEGORIES.map(({ icon, key, color }) => (
            <TouchableOpacity key={key} style={styles.categoryCard} onPress={() => startChat(key)}>
              <View style={[styles.categoryIcon, { backgroundColor: color + '15' }]}>
                <Ionicons name={icon} size={28} color={color} />
              </View>
              <BodyMedium style={styles.categoryTitle}>{t(`aids.${key}`)}</BodyMedium>
              <Caption style={styles.categoryDesc}>{t(`aids.${key}Desc`)}</Caption>
            </TouchableOpacity>
          ))}
        </View>

        {/* Quick questions */}
        <H3 style={styles.sectionTitle}>{t('aids.quickQuestions')}</H3>
        {[t('aids.q1'), t('aids.q2'), t('aids.q3')].map((q, i) => (
          <TouchableOpacity
            key={i}
            style={styles.questionCard}
            onPress={() => {
              setChatMode(true);
              setMessages([{ id: '0', role: 'model', text: t('aids.generalWelcome') }]);
              setInput(q);
            }}
          >
            <Ionicons name="chatbubble-ellipses-outline" size={20} color={colors.primary[500]} />
            <Body style={styles.questionText}>{q}</Body>
            <Ionicons name="chevron-forward" size={16} color={colors.neutral[400]} />
          </TouchableOpacity>
        ))}

        <View style={styles.disclaimer}>
          <Ionicons name="information-circle-outline" size={16} color={colors.neutral[400]} />
          <Caption style={styles.disclaimerText}>{t('aids.disclaimer')}</Caption>
        </View>
      </ScrollView>
    </SafeScreen>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  scrollContent: {
    paddingHorizontal: spacing.xl,
    paddingBottom: spacing['5xl'],
  },
  intro: {
    marginVertical: spacing.lg,
    lineHeight: 22,
  },
  grid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.md,
    marginBottom: spacing.xl,
  },
  categoryCard: {
    width: '47%',
    backgroundColor: colors.surface,
    borderRadius: radii['2xl'],
    padding: spacing.xl,
    ...shadows.sm,
  },
  categoryIcon: {
    width: 52,
    height: 52,
    borderRadius: 26,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: spacing.md,
  },
  categoryTitle: {
    marginBottom: spacing.xs,
    fontSize: 14,
  },
  categoryDesc: {
    fontSize: 11,
    color: colors.neutral[500],
    lineHeight: 16,
  },
  sectionTitle: {
    marginBottom: spacing.md,
  },
  questionCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.surface,
    padding: spacing.lg,
    borderRadius: radii.xl,
    marginBottom: spacing.sm,
    gap: spacing.md,
    ...shadows.sm,
  },
  questionText: {
    flex: 1,
    fontSize: 13,
  },
  disclaimer: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    gap: spacing.sm,
    marginTop: spacing.xl,
    padding: spacing.lg,
    backgroundColor: colors.neutral[50],
    borderRadius: radii.xl,
  },
  disclaimerText: { flex: 1, lineHeight: 16, fontSize: 11 },
  // Chat styles
  chatContent: {
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.md,
    paddingBottom: spacing.xl,
  },
  msgBubble: {
    marginBottom: spacing.md,
    maxWidth: '85%',
  },
  userBubble: { alignSelf: 'flex-end' },
  aiBubble: { alignSelf: 'flex-start' },
  bubbleContent: {
    padding: spacing.md,
    borderRadius: radii.xl,
  },
  userContent: {
    backgroundColor: colors.primary[500],
    borderBottomRightRadius: 4,
  },
  aiContent: {
    backgroundColor: colors.surface,
    borderBottomLeftRadius: 4,
    ...shadows.sm,
  },
  userText: { color: '#FFFFFF', fontSize: 14, lineHeight: 20 },
  aiText: { color: colors.neutral[800], fontSize: 14, lineHeight: 20 },
  inputBar: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.md,
    borderTopWidth: 1,
    borderTopColor: colors.neutral[100],
    backgroundColor: colors.surface,
    gap: spacing.sm,
  },
  textInput: {
    flex: 1,
    minHeight: 40,
    maxHeight: 100,
    backgroundColor: colors.neutral[50],
    borderRadius: radii.xl,
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.sm,
    fontSize: 14,
    color: colors.neutral[900],
  },
  sendBtn: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.primary[500],
    alignItems: 'center',
    justifyContent: 'center',
  },
  sendBtnDisabled: {
    backgroundColor: colors.neutral[200],
  },
});
