import { useState } from 'react';
import { View, Text, Pressable, TouchableOpacity, TextInput, Modal, StyleSheet, Platform, KeyboardAvoidingView, ScrollView } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useColors } from '../../lib/theme';

export interface SosFeedback {
  better: boolean | null;
  rating: number | null;
  text: string;
}

export function SosFeedbackModal({
  visible,
  onSubmit,
  onSkip,
}: {
  visible: boolean;
  onSubmit: (feedback: SosFeedback) => void;
  onSkip: () => void;
}) {
  const colors = useColors();
  const [better, setBetter] = useState<boolean | null>(null);
  const [rating, setRating] = useState<number>(0);
  const [text, setText] = useState('');

  function reset() {
    setBetter(null); setRating(0); setText('');
  }

  function submit() {
    onSubmit({ better, rating: rating > 0 ? rating : null, text: text.trim() });
    reset();
  }
  function skip() { onSkip(); reset(); }

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={skip}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={s.backdrop}
      >
        <ScrollView
          contentContainerStyle={s.scrollContent}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <View style={[s.card, { backgroundColor: colors.bg }]}>
            <Text style={[s.title, { color: colors.text }]}>Wie war diese Session?</Text>
            <Text style={[s.sub, { color: colors.textMuted }]}>Dein Feedback hilft Lyra besser zu werden.</Text>

            {/* Better Yes/No */}
            <Text style={[s.q, { color: colors.textMuted }]}>Fühlst du dich besser?</Text>
            <View style={s.btnRow}>
              <TouchableOpacity
                activeOpacity={0.7}
                style={[s.choiceBtn, better === true && s.choiceBtnYes]}
                onPress={() => setBetter(true)}
              >
                <Ionicons name="checkmark-circle" size={18} color={better === true ? '#fff' : '#16a34a'} />
                <Text style={[s.choiceTxt, better === true && { color: '#fff' }]}>Ja</Text>
              </TouchableOpacity>
              <TouchableOpacity
                activeOpacity={0.7}
                style={[s.choiceBtn, better === false && s.choiceBtnNo]}
                onPress={() => setBetter(false)}
              >
                <Ionicons name="close-circle" size={18} color={better === false ? '#fff' : '#dc2626'} />
                <Text style={[s.choiceTxt, better === false && { color: '#fff' }]}>Nein</Text>
              </TouchableOpacity>
            </View>

            {/* Stars */}
            <Text style={[s.q, { color: colors.textMuted }]}>Bewertung</Text>
            <View style={s.starsRow}>
              {[1, 2, 3, 4, 5].map((n) => (
                <TouchableOpacity key={n} onPress={() => setRating(n)} hitSlop={6} activeOpacity={0.7}>
                  <Ionicons
                    name={n <= rating ? 'star' : 'star-outline'}
                    size={32}
                    color={n <= rating ? '#f59e0b' : '#cbd5e1'}
                  />
                </TouchableOpacity>
              ))}
            </View>

            {/* Comment */}
            <Text style={[s.q, { color: colors.textMuted }]}>Bemerkung (optional)</Text>
            <TextInput
              style={[s.textArea, { backgroundColor: colors.surfaceElevated, borderColor: colors.border, color: colors.text }]}
              placeholder="Was war hilfreich? Was nicht?"
              placeholderTextColor="#94a3b8"
              multiline
              numberOfLines={3}
              value={text}
              onChangeText={setText}
              maxLength={500}
            />

            {/* Actions */}
            <View style={s.actions}>
              <TouchableOpacity activeOpacity={0.7} style={s.skipBtn} onPress={skip}>
                <Text style={s.skipTxt}>Überspringen</Text>
              </TouchableOpacity>
              <TouchableOpacity activeOpacity={0.7} style={[s.submitBtn, { backgroundColor: colors.brandOrange }]} onPress={submit}>
                <Text style={s.submitTxt}>Senden</Text>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </Modal>
  );
}

const s = StyleSheet.create({
  backdrop: { flex: 1, backgroundColor: 'rgba(0,0,0,0.45)' },
  scrollContent: { flexGrow: 1, alignItems: 'center', justifyContent: 'center', padding: 20 },
  card: { width: '100%', maxWidth: 420, backgroundColor: '#fff', borderRadius: 24, padding: 22, gap: 8, ...Platform.select({ ios: { shadowColor: '#000', shadowOffset: { width: 0, height: 10 }, shadowOpacity: 0.25, shadowRadius: 20 }, android: { elevation: 10 } }) },
  title: { fontFamily: 'Nunito_800ExtraBold', fontSize: 19, color: '#111827' },
  sub: { fontFamily: 'Nunito_400Regular', fontSize: 13, color: '#6b7280', marginBottom: 8 },
  q: { fontFamily: 'Nunito_700Bold', fontSize: 13, color: '#374151', marginTop: 12 },
  btnRow: { flexDirection: 'row', gap: 10, marginTop: 6 },
  choiceBtn: {
    flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 6,
    borderWidth: 1, borderColor: '#cbd5e1', backgroundColor: '#f1f5f9',
    borderRadius: 12, paddingVertical: 11,
  },
  choiceBtnYes: { backgroundColor: '#16a34a', borderColor: '#16a34a' },
  choiceBtnNo: { backgroundColor: '#dc2626', borderColor: '#dc2626' },
  choiceTxt: { fontFamily: 'Nunito_700Bold', fontSize: 14, color: '#374151' },
  starsRow: { flexDirection: 'row', justifyContent: 'center', gap: 8, marginTop: 8 },
  textArea: {
    marginTop: 6, backgroundColor: '#f8fafc', borderRadius: 12,
    borderWidth: 1, borderColor: '#e2e8f0',
    paddingHorizontal: 12, paddingVertical: 10, minHeight: 70,
    fontFamily: 'Nunito_400Regular', fontSize: 14, color: '#111827',
    textAlignVertical: 'top',
  },
  actions: { flexDirection: 'row', gap: 10, marginTop: 18 },
  skipBtn: { flex: 1, paddingVertical: 12, borderRadius: 12, alignItems: 'center', backgroundColor: '#f1f5f9' },
  skipTxt: { fontFamily: 'Nunito_700Bold', fontSize: 14, color: '#475569' },
  submitBtn: { flex: 2, paddingVertical: 12, borderRadius: 12, alignItems: 'center' },
  submitTxt: { fontFamily: 'Nunito_800ExtraBold', fontSize: 14, color: '#fff' },
});
