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

export interface ShareSuccessPayload {
  text: string;
}

/**
 * Bottom-Sheet zum Teilen einer Erfolgs-Story in der Community.
 * AI-generierter Vorschlagstext (vom Parent via prop), editierbar.
 */
export function ShareSuccessDrawer({
  initialText,
  generating,
  onShare,
  onClose,
  onRegenerate,
}: {
  initialText: string;
  generating: boolean;
  onShare: (text: string) => Promise<void> | void;
  onClose: () => void;
  onRegenerate?: () => void;
}) {
  const colors = useColors();
  const slide = useRef(new Animated.Value(600)).current;
  const [text, setText] = useState(initialText);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    Animated.spring(slide, {
      toValue: 0,
      useNativeDriver: true,
      damping: 22,
      mass: 1,
      stiffness: 200,
    }).start();
  }, []);

  // Sync wenn initialText neu generiert wird
  useEffect(() => {
    setText(initialText);
  }, [initialText]);

  async function handleShare() {
    if (!text.trim() || submitting) return;
    setSubmitting(true);
    try {
      await onShare(text.trim());
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <>
      <Pressable style={s.backdrop} onPress={onClose} />
      <Animated.View style={[s.drawer, { transform: [{ translateY: slide }], backgroundColor: colors.bg }]}>
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
          keyboardVerticalOffset={Platform.OS === 'ios' ? 24 : 0}
        >
          <View style={s.handle} />
          <ScrollView
            keyboardShouldPersistTaps="handled"
            showsVerticalScrollIndicator={false}
            contentContainerStyle={{ paddingBottom: 8 }}
          >
            <View style={s.header}>
              <Ionicons name="sparkles" size={20} color={colors.brandOrange} />
              <Text style={[s.title, { color: colors.text }]}>Erfolg teilen</Text>
            </View>
            <Text style={[s.sub, { color: colors.textMuted }]}>
              Inspiriere andere — dein Beitrag wird anonym in der Community gepostet.
            </Text>

            {generating ? (
              <View style={s.loadingBox}>
                <ActivityIndicator color={colors.brandOrange} />
                <Text style={s.loadingTxt}>Lyra schreibt einen Vorschlag…</Text>
              </View>
            ) : (
              <TextInput
                style={[s.textArea, { backgroundColor: colors.surfaceElevated, borderColor: colors.border, color: colors.text }]}
                multiline
                value={text}
                onChangeText={setText}
                maxLength={1000}
                placeholder="Schreib deine Erfolgs-Geschichte…"
                placeholderTextColor="#94a3b8"
              />
            )}

            <View style={s.row}>
              {onRegenerate && (
                <TouchableOpacity
                  activeOpacity={0.7}
                  style={s.secondaryBtn}
                  onPress={onRegenerate}
                  disabled={generating}
                >
                  <Ionicons name="refresh" size={16} color="#475569" />
                  <Text style={s.secondaryTxt}>Neu generieren</Text>
                </TouchableOpacity>
              )}
              <TouchableOpacity activeOpacity={0.7} style={s.cancelBtn} onPress={onClose}>
                <Text style={s.cancelTxt}>Abbrechen</Text>
              </TouchableOpacity>
              <TouchableOpacity
                activeOpacity={0.7}
                style={[s.shareBtn, { backgroundColor: colors.brandOrange }, (!text.trim() || submitting || generating) && s.shareBtnDisabled]}
                onPress={handleShare}
                disabled={!text.trim() || submitting || generating}
              >
                {submitting ? (
                  <ActivityIndicator color="#fff" size="small" />
                ) : (
                  <>
                    <Ionicons name="paper-plane" size={16} color="#fff" />
                    <Text style={s.shareTxt}>Teilen</Text>
                  </>
                )}
              </TouchableOpacity>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
      </Animated.View>
    </>
  );
}

const s = StyleSheet.create({
  backdrop: {
    position: 'absolute',
    top: 0, left: 0, right: 0, bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.35)',
  },
  drawer: {
    position: 'absolute',
    left: 0, right: 0, bottom: 0,
    backgroundColor: '#fff',
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    paddingHorizontal: 18,
    paddingTop: 8,
    paddingBottom: 22,
    maxHeight: '85%',
    ...Platform.select({
      ios: { shadowColor: '#000', shadowOffset: { width: 0, height: -4 }, shadowOpacity: 0.18, shadowRadius: 12 },
      android: { elevation: 12 },
    }),
  },
  handle: {
    width: 40, height: 4, borderRadius: 2,
    backgroundColor: '#e2e8f0',
    alignSelf: 'center',
    marginBottom: 12,
  },
  header: { flexDirection: 'row', alignItems: 'center', gap: 8 },
  title: { fontFamily: 'Nunito_800ExtraBold', fontSize: 19, color: '#111827' },
  sub: { fontFamily: 'Nunito_400Regular', fontSize: 13, color: '#6b7280', marginTop: 4, marginBottom: 12 },
  textArea: {
    backgroundColor: '#f8fafc',
    borderRadius: 14,
    borderWidth: 1, borderColor: '#e2e8f0',
    paddingHorizontal: 14, paddingVertical: 12,
    minHeight: 110, maxHeight: 220,
    fontFamily: 'Nunito_400Regular', fontSize: 15, color: '#111827',
    textAlignVertical: 'top',
  },
  loadingBox: {
    backgroundColor: '#f8fafc',
    borderRadius: 14, borderWidth: 1, borderColor: '#e2e8f0',
    paddingVertical: 28, paddingHorizontal: 14,
    alignItems: 'center', gap: 10,
    minHeight: 110,
    justifyContent: 'center',
  },
  loadingTxt: { fontFamily: 'Nunito_500Medium', fontSize: 13, color: '#64748b' },
  row: { flexDirection: 'row', alignItems: 'center', gap: 8, marginTop: 14, flexWrap: 'wrap' },
  secondaryBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 6,
    paddingHorizontal: 12, paddingVertical: 10,
    borderRadius: 12, backgroundColor: '#f1f5f9',
    borderWidth: 1, borderColor: '#cbd5e1',
  },
  secondaryTxt: { fontFamily: 'Nunito_700Bold', fontSize: 13, color: '#475569' },
  cancelBtn: {
    paddingHorizontal: 14, paddingVertical: 10,
    borderRadius: 12, backgroundColor: '#f1f5f9',
  },
  cancelTxt: { fontFamily: 'Nunito_700Bold', fontSize: 13, color: '#475569' },
  shareBtn: {
    flex: 1, minWidth: 110,
    flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 6,
    borderRadius: 12, paddingVertical: 12,
  },
  shareBtnDisabled: { opacity: 0.5 },
  shareTxt: { fontFamily: 'Nunito_800ExtraBold', fontSize: 14, color: '#fff' },
});
