import { useState } from 'react';
import { Linking, Text, TouchableOpacity, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { useColors } from '../lib/theme';
import { FormSheet } from './FormSheet';

/**
 * iOS-spezifischer Recovery-Sheet wenn NEFilter-Aktivierung mit
 * NEFilterErrorDomain code 5 (Permission denied) fehlschlägt.
 *
 * iOS cached "Refuser" einmalig — der System-Dialog kommt beim normalen
 * activateUrlFilter nicht mehr. Sheet bietet zwei Recovery-Pfade:
 *  1. „Erneut versuchen" → ruft protection.resetUrlFilter() (Swift macht
 *     removeFromPreferences + frisches saveToPreferences → meist frischer Dialog)
 *  2. „Einstellungen öffnen" → Deep-Link via Linking.openURL('app-settings:')
 *     wenn auch Reset nicht hilft (z.B. Screen-Time-Restrictions)
 *
 * Plus ein 3-Step-Fallback-Hinweis für den Härtefall (App neu installieren).
 */
export type PermissionDeniedVariant = 'nefilter' | 'family_controls';

export function PermissionDeniedSheet({
  visible,
  onClose,
  onRetry,
  variant = 'nefilter',
}: {
  visible: boolean;
  onClose: () => void;
  /** wird aufgerufen wenn User „Erneut versuchen" tappt — soll protection.resetUrlFilter()
   * bzw. protection.activateFamilyControls() callen (je nach variant) */
  onRetry: () => Promise<{ enabled: boolean; error?: string }>;
  /** Default 'nefilter' (URL-Filter denied). 'family_controls' = App-Lock-XPC-4099-Issue */
  variant?: PermissionDeniedVariant;
}) {
  const colors = useColors();
  const { t } = useTranslation();
  const [retrying, setRetrying] = useState(false);

  // i18n-Keys per Variant — eigenes namespace damit DE/EN/FR/AR separat verfasst werden können.
  const ns =
    variant === 'family_controls' ? 'blocker.family_controls_error' : 'blocker.permission_denied';

  async function handleRetry() {
    if (retrying) return;
    setRetrying(true);
    try {
      const res = await onRetry();
      if (res.enabled) {
        // Erfolg — Sheet kann schließen, Outer-Page refresht den Status selbst.
        onClose();
      }
      // Bei error: Sheet bleibt offen, User kann „Einstellungen öffnen" oder erneut versuchen.
    } finally {
      setRetrying(false);
    }
  }

  function openSettings() {
    Linking.openURL('app-settings:').catch(() => {});
  }

  return (
    <FormSheet
      visible={visible}
      onClose={onClose}
      title={t(`${ns}.title`)}
      initialHeightPct={0.62}
      minHeightPct={0.35}
    >
      <View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 4, paddingBottom: 16 }}>
        {/* Icon-Header */}
        <View style={{ alignItems: 'center', marginTop: 8, marginBottom: 16 }}>
          <View
            style={{
              width: 64,
              height: 64,
              borderRadius: 18,
              backgroundColor: 'rgba(245,158,11,0.12)',
              borderWidth: 1,
              borderColor: 'rgba(245,158,11,0.30)',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Ionicons name="shield-outline" size={32} color={colors.warning} />
          </View>
        </View>

        {/* Body */}
        <Text
          style={{
            fontFamily: 'Nunito_400Regular',
            fontSize: 14,
            lineHeight: 21,
            color: colors.text,
            textAlign: 'center',
            marginBottom: 18,
          }}
        >
          {t(`${ns}.body`)}
        </Text>

        {/* Primary Retry */}
        <TouchableOpacity
          onPress={handleRetry}
          disabled={retrying}
          activeOpacity={0.85}
          style={{
            backgroundColor: colors.brandOrange,
            borderRadius: 14,
            paddingVertical: 14,
            alignItems: 'center',
            marginBottom: 10,
            opacity: retrying ? 0.6 : 1,
          }}
        >
          <Text
            style={{
              fontFamily: 'Nunito_700Bold',
              fontSize: 15,
              color: '#ffffff',
            }}
          >
            {retrying
              ? t(`${ns}.retry_loading`)
              : t(`${ns}.retry_cta`)}
          </Text>
        </TouchableOpacity>

        {/* Secondary Settings */}
        <TouchableOpacity
          onPress={openSettings}
          activeOpacity={0.7}
          style={{
            backgroundColor: colors.surfaceElevated,
            borderRadius: 14,
            paddingVertical: 14,
            alignItems: 'center',
            marginBottom: 16,
          }}
        >
          <Text
            style={{
              fontFamily: 'Nunito_600SemiBold',
              fontSize: 14,
              color: colors.text,
            }}
          >
            {t(`${ns}.settings_cta`)}
          </Text>
        </TouchableOpacity>

        {/* Fallback-Hinweis */}
        <View
          style={{
            backgroundColor: colors.surfaceElevated,
            borderRadius: 12,
            paddingVertical: 12,
            paddingHorizontal: 14,
          }}
        >
          <Text
            style={{
              fontFamily: 'Nunito_700Bold',
              fontSize: 12,
              color: colors.textMuted,
              letterSpacing: 0.5,
              textTransform: 'uppercase',
              marginBottom: 6,
            }}
          >
            {t(`${ns}.fallback_label`)}
          </Text>
          <Text
            style={{
              fontFamily: 'Nunito_400Regular',
              fontSize: 12,
              lineHeight: 18,
              color: colors.textMuted,
            }}
          >
            {t(`${ns}.fallback_body`)}
          </Text>
        </View>
      </View>
    </FormSheet>
  );
}
