import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Shield, Bell, LogOut, User } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { MobileShell } from './components/MobileShell';
import { MobileCard, CTAButton, PillBadge } from './components/Primitives';
import { useAuth } from '../auth/context';
import {
  getNotificationPreferences,
  updateNotificationPreferences,
  NotificationPreferences,
} from '../api';
import { getApiErrorMessage } from '../lib/apiError';
import { adminPath } from '../constants';

type PreferenceKey = keyof NotificationPreferences;

export default function MobileSettingsPage() {
  const { t } = useTranslation('management');
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  const [preferences, setPreferences] = React.useState<NotificationPreferences>({});
  const [defaults, setDefaults] = React.useState<NotificationPreferences>({});
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    (async () => {
      setLoading(true);
      try {
        const result = await getNotificationPreferences();
        setPreferences(result.preferences);
        setDefaults(result.defaults ?? {});
        setError(null);
      } catch (err) {
        setError(getApiErrorMessage(err, t('settings.notifications.errorLoad', 'Benachrichtigungen konnten nicht geladen werden.')));
      } finally {
        setLoading(false);
      }
    })();
  }, [t]);

  const togglePref = (key: PreferenceKey) => {
    setPreferences((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await updateNotificationPreferences(preferences);
      setError(null);
    } catch (err) {
      setError(getApiErrorMessage(err, t('settings.notifications.errorSave', 'Speichern fehlgeschlagen')));
    } finally {
      setSaving(false);
    }
  };

  const handleReset = () => {
    setPreferences(defaults);
  };

  return (
    <MobileShell activeTab="profile" title={t('mobileSettings.title', 'Settings')} onBack={() => navigate(-1)}>
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color="#b91c1c">
            {error}
          </Text>
        </MobileCard>
      ) : null}

      <MobileCard space="$3">
        <XStack alignItems="center" space="$2">
          <Shield size={18} color="#0f172a" />
          <Text fontSize="$md" fontWeight="800" color="#0f172a">
            {t('mobileSettings.accountTitle', 'Account')}
          </Text>
        </XStack>
        <Text fontSize="$sm" color="#4b5563">
          {user?.name ?? user?.email ?? t('settings.session.unknown', 'Benutzer')}
        </Text>
        {user?.tenant_id ? (
          <PillBadge tone="muted">{t('mobileSettings.tenantBadge', 'Tenant #{{id}}', { id: user.tenant_id })}</PillBadge>
        ) : null}
        <XStack space="$2">
          <CTAButton label={t('settings.profile.actions.openProfile', 'Profil bearbeiten')} onPress={() => navigate(adminPath('/mobile/profile'))} />
          <CTAButton label={t('settings.session.logout', 'Abmelden')} tone="ghost" onPress={() => logout({ redirect: adminPath('/logout') })} />
        </XStack>
      </MobileCard>

      <MobileCard space="$3">
        <XStack alignItems="center" space="$2">
          <Bell size={18} color="#0f172a" />
          <Text fontSize="$md" fontWeight="800" color="#0f172a">
            {t('mobileSettings.notificationsTitle', 'Notifications')}
          </Text>
        </XStack>
        {loading ? (
          <Text fontSize="$sm" color="#6b7280">
            {t('mobileSettings.notificationsLoading', 'Loading settings ...')}
          </Text>
        ) : (
          <YStack space="$2">
            {(['task_updates','photo_limits','photo_thresholds','guest_limits','guest_thresholds','purchase_limits','billing','alerts'] as PreferenceKey[]).map((key) => {
              const prefKey = key as PreferenceKey;
              return (
                <XStack key={prefKey} alignItems="center" justifyContent="space-between" borderBottomWidth={1} borderColor="#e5e7eb" paddingBottom="$2" paddingTop="$1.5">
                  <Text fontSize="$sm" color="#0f172a">
                    {t(`mobileSettings.pref.${prefKey}`, prefKey)}
                  </Text>
                  <input
                    type="checkbox"
                    checked={Boolean(preferences[prefKey])}
                    onChange={() => togglePref(prefKey)}
                  />
                </XStack>
              );
            })}
          </YStack>
        )}
        <XStack space="$2">
          <CTAButton label={saving ? t('common.processing', '...') : t('settings.notifications.actions.save', 'Speichern')} onPress={() => handleSave()} />
          <CTAButton label={t('common.reset', 'Reset')} tone="ghost" onPress={() => handleReset()} />
        </XStack>
      </MobileCard>

      <MobileCard space="$3">
        <XStack alignItems="center" space="$2">
          <User size={18} color="#0f172a" />
          <Text fontSize="$md" fontWeight="800" color="#0f172a">
            {t('settings.appearance.title', 'Darstellung')}
          </Text>
        </XStack>
        <Text fontSize="$sm" color="#4b5563">
          {t('settings.appearance.description', 'Schalte Dark-Mode oder passe Branding im Admin an.')}
        </Text>
        <CTAButton label={t('settings.appearance.title', 'Darstellung & Branding')} tone="ghost" onPress={() => navigate(adminPath('/settings'))} />
      </MobileCard>
    </MobileShell>
  );
}
