import { useEffect, useRef, useState } from 'react';
import { ActivityIndicator, Switch, Text, TouchableOpacity, View } from 'react-native';
import { TrueSheet, type SheetDetent } from '@lodev09/react-native-true-sheet';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'expo-router';
import { apiFetch } from '../../lib/api';
import { useColors } from '../../lib/theme';

const CONSENT_VERSION = 'art9-mail-v1-2026-05-13';

type PendingConnection = {
  id: string;
  email: string;
};

type Props = {
  connections: PendingConnection[];
  onDismiss: () => void;
  onConsented: () => void;
};

export function MailConsentReminderSheet({ connections, onDismiss, onConsented }: Props) {
  const { t } = useTranslation();
  const colors = useColors();
  const router = useRouter();
  const sheetRef = useRef<TrueSheet>(null);
  const [consentGiven, setConsentGiven] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (connections.length > 0) {
      sheetRef.current?.present();
    }
  }, [connections.length]);

  async function handleConsent() {
    if (!consentGiven || submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      await apiFetch('/api/mail-connections/consent', {
        method: 'POST',
        body: {
          mailConnectionId: connections.map((c) => c.id),
          consentVersion: CONSENT_VERSION,
        },
      });
      sheetRef.current?.dismiss();
      onConsented();
    } catch {
      setError(t('mail.consent.reminder_consent_error'));
    } finally {
      setSubmitting(false);
    }
  }

  function handleLater() {
    sheetRef.current?.dismiss();
    onDismiss();
  }

  function handleDisconnect() {
    sheetRef.current?.dismiss();
    onDismiss();
    router.push('/(app)/mail');
  }

  const count = connections.length;
  const bodyText =
    count === 1
      ? t('mail.consent.reminder_body_one')
      : t('mail.consent.reminder_body_other', { count });

  return (
    <TrueSheet
      ref={sheetRef}
      detents={['auto', 1] satisfies SheetDetent[]}
      cornerRadius={20}
      grabber
      onDidDismiss={onDismiss}
    >
      <View style={{ paddingHorizontal: 20, paddingTop: 8, paddingBottom: 40, gap: 16 }}>
        <View
          style={{
            width: 44,
            height: 44,
            borderRadius: 12,
            backgroundColor: 'rgba(245,158,11,0.12)',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <Ionicons name="lock-closed-outline" size={22} color="#b45309" />
        </View>

        <View style={{ gap: 6 }}>
          <Text
            style={{
              fontSize: 20,
              fontFamily: 'Nunito_700Bold',
              color: colors.text,
            }}
          >
            {t('mail.consent.reminder_title')}
          </Text>
          <Text
            style={{
              fontSize: 14,
              fontFamily: 'Nunito_400Regular',
              color: colors.textMuted,
              lineHeight: 20,
            }}
          >
            {bodyText}
          </Text>
        </View>

        <View
          style={{
            backgroundColor: '#fefce8',
            borderRadius: 12,
            borderWidth: 1,
            borderColor: '#fde68a',
            padding: 14,
            gap: 12,
          }}
        >
          <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12 }}>
            <Switch
              value={consentGiven}
              onValueChange={setConsentGiven}
              trackColor={{ false: '#d1d5db', true: '#16a34a' }}
              thumbColor="#fff"
            />
            <TouchableOpacity
              activeOpacity={0.7}
              onPress={() => setConsentGiven((v) => !v)}
              style={{ flex: 1 }}
            >
              <Text
                style={{
                  fontSize: 13,
                  fontFamily: 'Nunito_400Regular',
                  color: '#78350f',
                  lineHeight: 18,
                }}
              >
                {t('mail.consent.reminder_legal_short')}
              </Text>
            </TouchableOpacity>
          </View>
        </View>

        {error ? (
          <Text
            style={{
              fontSize: 13,
              fontFamily: 'Nunito_400Regular',
              color: colors.error,
            }}
          >
            {error}
          </Text>
        ) : null}

        <TouchableOpacity
          activeOpacity={consentGiven && !submitting ? 0.85 : 1}
          onPress={handleConsent}
          disabled={!consentGiven || submitting}
        >
          <View
            style={{
              backgroundColor: consentGiven && !submitting ? '#007AFF' : '#d4d4d4',
              borderRadius: 14,
              paddingVertical: 14,
              alignItems: 'center',
            }}
          >
            {submitting ? (
              <ActivityIndicator color="#fff" />
            ) : (
              <Text style={{ fontSize: 15, fontFamily: 'Nunito_700Bold', color: '#fff' }}>
                {t('mail.consent.reminder_cta_consent')}
              </Text>
            )}
          </View>
        </TouchableOpacity>

        <View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 12 }}>
          <TouchableOpacity activeOpacity={0.7} onPress={handleLater} style={{ flex: 1 }}>
            <View
              style={{
                borderRadius: 14,
                paddingVertical: 12,
                alignItems: 'center',
                backgroundColor: colors.surfaceElevated,
              }}
            >
              <Text
                style={{
                  fontSize: 14,
                  fontFamily: 'Nunito_600SemiBold',
                  color: colors.textMuted,
                }}
              >
                {t('mail.consent.reminder_cta_later')}
              </Text>
            </View>
          </TouchableOpacity>

          <TouchableOpacity activeOpacity={0.7} onPress={handleDisconnect} style={{ flex: 1 }}>
            <View
              style={{
                borderRadius: 14,
                paddingVertical: 12,
                alignItems: 'center',
                backgroundColor: 'rgba(220,38,38,0.08)',
              }}
            >
              <Text
                style={{
                  fontSize: 14,
                  fontFamily: 'Nunito_600SemiBold',
                  color: colors.error,
                }}
              >
                {t('mail.consent.reminder_cta_disconnect')}
              </Text>
            </View>
          </TouchableOpacity>
        </View>
      </View>
    </TrueSheet>
  );
}
