import { useState, useEffect, useRef } from 'react';
import {
  Modal,
  View,
  Text,
  TextInput,
  Pressable,
  KeyboardAvoidingView,
  Platform,
  Image,
  ActivityIndicator,
  Animated,
  Dimensions,
  Easing,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import {
  isValidDomain,
  normalizeDomain,
  type Tier,
} from '../../hooks/useCustomDomains';
import { useColors } from '../../lib/theme';

const SCREEN_HEIGHT = Dimensions.get('window').height;
const SHEET_HEIGHT = SCREEN_HEIGHT * 0.65; // wie bei PostCommentsSheet — 65% der Screen-Höhe

type Props = {
  visible: boolean;
  tier: Tier;
  onClose: () => void;
  onAdd: (domain: string) => Promise<{ ok: boolean; error?: string; alreadyGlobal?: boolean }>;
};

export function AddDomainSheet({ visible, tier, onClose, onAdd }: Props) {
  const { t } = useTranslation();
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const [input, setInput] = useState('');
  const [confirmPermanent, setConfirmPermanent] = useState(false);
  const [adding, setAdding] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const valid = isValidDomain(input);
  const normalized = normalizeDomain(input);

  // Slide-up Animation für die Sheet (translateY von SHEET_HEIGHT → 0)
  const translateY = useRef(new Animated.Value(SHEET_HEIGHT)).current;
  const backdropOpacity = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (visible) {
      translateY.setValue(SHEET_HEIGHT);
      backdropOpacity.setValue(0);
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: 0,
          duration: 280,
          easing: Easing.out(Easing.cubic),
          useNativeDriver: true,
        }),
        Animated.timing(backdropOpacity, {
          toValue: 1,
          duration: 220,
          useNativeDriver: true,
        }),
      ]).start();
    }
  }, [visible, translateY, backdropOpacity]);

  function close() {
    setInput('');
    setConfirmPermanent(false);
    setError(null);
    onClose();
  }

  async function handleAdd() {
    if (!valid || !confirmPermanent || adding) return;
    setAdding(true);
    setError(null);
    const result = await onAdd(input);
    setAdding(false);
    if (result.ok) {
      close();
      return;
    }
    if (result.alreadyGlobal) {
      setError(t('blocker.add_sheet_already_global', { domain: normalized }));
    } else {
      setError(result.error ?? t('blocker.add_sheet_add_failed'));
    }
  }

  const warningText =
    tier.plan === 'free'
      ? t('blocker.add_sheet_warning_free')
      : t('blocker.add_sheet_warning_pro');

  return (
    <Modal visible={visible} transparent animationType="none" onRequestClose={close}>
      {/* Backdrop — Tap-outside schließt */}
      <Animated.View
        style={{
          position: 'absolute',
          inset: 0 as any,
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0,0,0,0.4)',
          opacity: backdropOpacity,
        }}
      >
        <Pressable style={{ flex: 1 }} onPress={close} />
      </Animated.View>

      {/* Sheet — slide-up von unten, 65% der Screen-Höhe */}
      <Animated.View
        style={{
          position: 'absolute',
          left: 0,
          right: 0,
          bottom: 0,
          height: SHEET_HEIGHT,
          backgroundColor: colors.bg,
          borderTopLeftRadius: 20,
          borderTopRightRadius: 20,
          transform: [{ translateY }],
        }}
      >
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : undefined}
          style={{ flex: 1 }}
        >
          {/* Drag-handle */}
          <View style={{ alignItems: 'center', paddingTop: 8, paddingBottom: 4 }}>
            <View style={{ width: 36, height: 4, borderRadius: 2, backgroundColor: colors.border }} />
          </View>

          {/* Header */}
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingHorizontal: 16,
              paddingTop: 6,
              paddingBottom: 12,
              borderBottomWidth: 1,
              borderBottomColor: colors.border,
            }}
          >
            <Pressable onPress={close} hitSlop={10}>
              <Text style={{ fontSize: 16, fontFamily: 'Nunito_400Regular', color: colors.textMuted }}>
                {t('common.cancel')}
              </Text>
            </Pressable>
            <Text style={{ fontSize: 16, fontFamily: 'Nunito_700Bold', color: colors.text }}>
              {t('blocker.add_sheet_title')}
            </Text>
            <View style={{ width: 60 }} />
          </View>

          <View style={{ flex: 1, padding: 20, gap: 14 }}>
            {/* Input */}
            <View>
              <Text
                style={{
                  fontSize: 12,
                  fontFamily: 'Nunito_600SemiBold',
                  color: colors.textMuted,
                  marginBottom: 6,
                }}
              >
                {t('blocker.add_sheet_label')}
              </Text>
              <TextInput
                value={input}
                onChangeText={(v) => {
                  setInput(v);
                  setError(null);
                }}
                placeholder={t('blocker.add_sheet_placeholder')}
                placeholderTextColor={colors.textMuted}
                autoCapitalize="none"
                autoCorrect={false}
                autoFocus
                keyboardType="url"
                returnKeyType="done"
                onSubmitEditing={handleAdd}
                style={{
                  backgroundColor: colors.surfaceElevated,
                  borderRadius: 12,
                  paddingHorizontal: 14,
                  paddingVertical: 12,
                  fontSize: 15,
                  fontFamily: 'Nunito_400Regular',
                  color: colors.text,
                }}
              />
              {input && !valid && (
                <Text
                  style={{
                    fontSize: 12,
                    fontFamily: 'Nunito_400Regular',
                    color: '#dc2626',
                    marginTop: 6,
                  }}
                >
                  {t('blocker.add_sheet_invalid')}
                </Text>
              )}
            </View>

            {/* Preview */}
            {valid && (
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 10,
                  padding: 12,
                  backgroundColor: colors.surfaceElevated,
                  borderRadius: 12,
                }}
              >
                <Image
                  source={{
                    uri: `https://www.google.com/s2/favicons?domain=${normalized}&sz=64`,
                  }}
                  style={{ width: 24, height: 24, borderRadius: 4 }}
                />
                <Text
                  style={{
                    flex: 1,
                    fontSize: 14,
                    fontFamily: 'Nunito_600SemiBold',
                    color: colors.text,
                  }}
                  numberOfLines={1}
                >
                  {normalized}
                </Text>
              </View>
            )}

            {/* Warning */}
            {valid && (
              <View
                style={{
                  flexDirection: 'row',
                  gap: 10,
                  padding: 12,
                  backgroundColor: '#fef3c7',
                  borderRadius: 12,
                  borderWidth: 1,
                  borderColor: '#fcd34d',
                }}
              >
                <Ionicons name="lock-closed" size={18} color="#92400e" />
                <Text
                  style={{
                    flex: 1,
                    fontSize: 12,
                    fontFamily: 'Nunito_400Regular',
                    color: '#92400e',
                    lineHeight: 17,
                  }}
                >
                  {warningText}
                </Text>
              </View>
            )}

            {/* Confirm-Checkbox */}
            {valid && (
              <Pressable
                onPress={() => setConfirmPermanent((v) => !v)}
                style={{
                  flexDirection: 'row',
                  alignItems: 'flex-start',
                  gap: 10,
                  paddingVertical: 4,
                }}
              >
                <View
                  style={{
                    width: 22,
                    height: 22,
                    borderRadius: 6,
                    borderWidth: 1.5,
                    borderColor: confirmPermanent ? colors.success : colors.border,
                    backgroundColor: confirmPermanent ? colors.success : colors.bg,
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginTop: 1,
                  }}
                >
                  {confirmPermanent && <Ionicons name="checkmark" size={16} color="#fff" />}
                </View>
                <Text
                  style={{
                    flex: 1,
                    fontSize: 13,
                    fontFamily: 'Nunito_400Regular',
                    color: colors.text,
                    lineHeight: 18,
                  }}
                >
                  {t('blocker.add_sheet_confirm_permanent')}
                </Text>
              </Pressable>
            )}

            {/* Error */}
            {error && (
              <Text
                style={{ fontSize: 13, fontFamily: 'Nunito_400Regular', color: '#dc2626' }}
              >
                {error}
              </Text>
            )}

            <View style={{ flex: 1 }} />

            {/* Add-Button */}
            <Pressable
              onPress={handleAdd}
              disabled={!valid || !confirmPermanent || adding}
              style={({ pressed }) => ({
                opacity: pressed ? 0.85 : 1,
                marginBottom: insets.bottom > 0 ? 8 : 12,
              })}
            >
              <View style={{
                backgroundColor: !valid || !confirmPermanent ? '#d4d4d4' : '#dc2626',
                borderRadius: 14,
                paddingVertical: 14,
                alignItems: 'center',
              }}>
                {adding ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <Text style={{ fontSize: 15, fontFamily: 'Nunito_700Bold', color: '#fff' }}>
                    {t('blocker.add_sheet_title')}
                  </Text>
                )}
              </View>
            </Pressable>
          </View>
        </KeyboardAvoidingView>
      </Animated.View>
    </Modal>
  );
}
