import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { LogOut, User, Settings, Shield, Globe, Moon, Download } 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 { YGroup } from '@tamagui/group';
import { ListItem } from '@tamagui/list-item';
import { MobileShell } from './components/MobileShell';
import { MobileCard, CTAButton } from './components/Primitives';
import { MobileSelect } from './components/FormControls';
import { useAuth } from '../auth/context';
import { fetchTenantProfile } from '../api';
import { adminPath, ADMIN_DATA_EXPORTS_PATH } from '../constants';
import i18n from '../i18n';
import { useAppearance } from '@/hooks/use-appearance';
import { useBackNavigation } from './hooks/useBackNavigation';
import { useAdminTheme } from './theme';

export default function MobileProfilePage() {
  const { user, logout } = useAuth();
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const { appearance, updateAppearance } = useAppearance();
  const { textStrong, muted, border, accentSoft, primary, subtle } = useAdminTheme();
  const textColor = textStrong;
  const mutedText = muted;
  const borderColor = border;
  const avatarBg = accentSoft;
  const back = useBackNavigation(adminPath('/mobile/dashboard'));

  const [name, setName] = React.useState(user?.name ?? t('events.members.roles.guest', 'Guest'));
  const [email, setEmail] = React.useState(user?.email ?? '');
  const [role, setRole] = React.useState<string>(user?.role ?? '');
  const [language, setLanguage] = React.useState<string>(i18n.language || 'de');

  React.useEffect(() => {
    (async () => {
      try {
        const profile = await fetchTenantProfile();
        setName(profile.name ?? name);
        setEmail(profile.email ?? email);
        setRole((profile as any)?.role ?? role);
      } catch {
        // non-fatal for mobile profile view
      }
    })();
  }, [email, name, role]);

  return (
    <MobileShell
      activeTab="profile"
      title={t('mobileProfile.title', 'Profile')}
      onBack={back}
    >
      <MobileCard space="$3" alignItems="center">
        <XStack
          width={64}
          height={64}
          borderRadius={20}
          alignItems="center"
          justifyContent="center"
          backgroundColor={avatarBg}
        >
          <User size={28} color={primary} />
        </XStack>
        <Text fontSize="$md" fontWeight="800" color={textColor}>
          {name}
        </Text>
        <Text fontSize="$sm" color={mutedText}>
          {email}
        </Text>
        {role ? (
          <Text fontSize="$xs" color={mutedText}>
            {role}
          </Text>
        ) : null}
      </MobileCard>

      <MobileCard space="$3">
        <Text fontSize="$md" fontWeight="800" color={textColor}>
          {t('mobileProfile.settings', 'Settings')}
        </Text>
        <YGroup borderRadius="$4" borderWidth={1} borderColor={borderColor} overflow="hidden">
          <YGroup.Item bordered>
            <Pressable onPress={() => navigate(adminPath('/mobile/settings'))}>
              <ListItem
                hoverTheme
                pressTheme
                paddingVertical="$2"
                paddingHorizontal="$3"
                title={
                  <Text fontSize="$sm" color={textColor}>
                    {t('mobileProfile.account', 'Account & security')}
                  </Text>
                }
                iconAfter={<Settings size={18} color={subtle} />}
              />
            </Pressable>
          </YGroup.Item>
          <YGroup.Item bordered>
            <Pressable onPress={() => navigate(adminPath('/mobile/billing#packages'))}>
              <ListItem
                hoverTheme
                pressTheme
                paddingVertical="$2"
                paddingHorizontal="$3"
                title={
                  <Text fontSize="$sm" color={textColor}>
                    {t('billing.sections.packages.title', 'Packages & Billing')}
                  </Text>
                }
                iconAfter={<Settings size={18} color={subtle} />}
              />
            </Pressable>
          </YGroup.Item>
          <YGroup.Item bordered>
            <Pressable onPress={() => navigate(adminPath('/mobile/billing#invoices'))}>
              <ListItem
                hoverTheme
                pressTheme
                paddingVertical="$2"
                paddingHorizontal="$3"
                title={
                  <Text fontSize="$sm" color={textColor}>
                    {t('billing.sections.invoices.title', 'Invoices & Payments')}
                  </Text>
                }
                iconAfter={<Settings size={18} color={subtle} />}
              />
            </Pressable>
          </YGroup.Item>
          <YGroup.Item bordered>
            <Pressable onPress={() => navigate(ADMIN_DATA_EXPORTS_PATH)}>
              <ListItem
                hoverTheme
                pressTheme
                paddingVertical="$2"
                paddingHorizontal="$3"
                title={
                  <Text fontSize="$sm" color={textColor}>
                    {t('dataExports.title', 'Data exports')}
                  </Text>
                }
                iconAfter={<Download size={18} color={subtle} />}
              />
            </Pressable>
          </YGroup.Item>
          <YGroup.Item bordered>
            <ListItem
              paddingVertical="$2"
              paddingHorizontal="$3"
              title={
                <XStack space="$2" alignItems="center">
                  <Globe size={16} color={muted} />
                  <Text fontSize="$sm" color={textColor}>
                    {t('mobileProfile.language', 'Language')}
                  </Text>
                </XStack>
              }
              iconAfter={
                <MobileSelect
                  value={language}
                  onChange={(e) => {
                    const lng = e.target.value;
                    setLanguage(lng);
                    void i18n.changeLanguage(lng);
                  }}
                  compact
                  style={{ minWidth: 130 }}
                >
                  <option value="de">{t('mobileProfile.languageDe', 'Deutsch')}</option>
                  <option value="en">{t('mobileProfile.languageEn', 'English')}</option>
                </MobileSelect>
              }
            />
          </YGroup.Item>
          <YGroup.Item>
            <ListItem
              paddingVertical="$2"
              paddingHorizontal="$3"
              title={
                <XStack space="$2" alignItems="center">
                  <Moon size={16} color={muted} />
                  <Text fontSize="$sm" color={textColor}>
                    {t('mobileProfile.theme', 'Theme')}
                  </Text>
                </XStack>
              }
              iconAfter={
                <MobileSelect
                  value={appearance}
                  onChange={(e) => updateAppearance(e.target.value as 'light' | 'dark' | 'system')}
                  compact
                  style={{ minWidth: 130 }}
                >
                  <option value="light">{t('mobileProfile.themeLight', 'Light')}</option>
                  <option value="dark">{t('mobileProfile.themeDark', 'Dark')}</option>
                  <option value="system">{t('mobileProfile.themeSystem', 'System')}</option>
                </MobileSelect>
              }
            />
          </YGroup.Item>
        </YGroup>
      </MobileCard>

      <CTAButton
        label={t('mobileProfile.logout', 'Log out')}
        onPress={() => {
          logout();
          navigate(adminPath('/logout'));
        }}
      />
    </MobileShell>
  );
}
