import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { User, Settings, Globe, Moon, Download, LogOut } from 'lucide-react';
import { Avatar } from '@tamagui/avatar';
import { Card } from '@tamagui/card';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { YGroup } from '@tamagui/group';
import { ListItem } from '@tamagui/list-item';
import { MobileShell } from './components/MobileShell';
import { CTAButton } from './components/Primitives';
import { MobileSelect } from './components/FormControls';
import { useAuth } from '../auth/context';
import { fetchTenantProfile } from '../api';
import { adminPath, ADMIN_DATA_EXPORTS_PATH, ADMIN_PROFILE_ACCOUNT_PATH } from '../constants';
import i18n from '../i18n';
import { useAppearance } from '@/hooks/use-appearance';
import { useBackNavigation } from './hooks/useBackNavigation';
import { withAlpha } from './components/colors';
import { useAdminTheme } from './theme';

export default function MobileProfilePage() {
  const { user, logout } = useAuth();
  const isMember = user?.role === 'member';
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const { appearance, updateAppearance } = useAppearance();
  const { textStrong, muted, border, accentSoft, primary, subtle, surface, surfaceMuted, shadow, danger } = 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}
    >
      <Card
        borderRadius={22}
        borderWidth={2}
        borderColor={borderColor}
        backgroundColor={surface}
        padding="$3"
        shadowColor={shadow}
        shadowOpacity={0.16}
        shadowRadius={16}
        shadowOffset={{ width: 0, height: 10 }}
      >
        <YStack space="$2.5" alignItems="center">
          <Avatar size="$7" borderRadius={20} backgroundColor={avatarBg}>
            <Avatar.Fallback>
              <User size={28} color={primary} />
            </Avatar.Fallback>
          </Avatar>
          <YStack space="$0.5" alignItems="center">
            <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}
          </YStack>
        </YStack>
      </Card>

      <Card
        borderRadius={22}
        borderWidth={2}
        borderColor={borderColor}
        backgroundColor={surface}
        padding="$3"
        shadowColor={shadow}
        shadowOpacity={0.16}
        shadowRadius={16}
        shadowOffset={{ width: 0, height: 10 }}
      >
        <YStack space="$2.5">
          <XStack
            alignItems="center"
            paddingHorizontal="$3"
            paddingVertical="$1.5"
            borderRadius={999}
            borderWidth={1}
            borderColor={borderColor}
            backgroundColor={surfaceMuted}
          >
            <Text fontSize="$xs" fontWeight="800" color={textColor}>
              {t('mobileProfile.settings', 'Settings')}
            </Text>
          </XStack>
          <YGroup {...({ borderRadius: "$4", borderWidth: 1, borderColor: borderColor, overflow: "hidden" } as any)}>
            <YGroup.Item>
              <ListItem
                hoverTheme
                pressTheme
                paddingVertical="$2"
                paddingHorizontal="$3"
                title={
                  <Text fontSize="$sm" color={textColor}>
                    {t('mobileProfile.account', 'Account bearbeiten')}
                  </Text>
                }
                iconAfter={<Settings size={18} color={subtle} />}
                onPress={() => navigate(ADMIN_PROFILE_ACCOUNT_PATH)}
              />
            </YGroup.Item>
            {!isMember ? (
              <>
                <YGroup.Item>
                  <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} />}
                    onPress={() => navigate(adminPath('/mobile/billing#packages'))}
                  />
                </YGroup.Item>
                <YGroup.Item>
                  <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} />}
                    onPress={() => navigate(adminPath('/mobile/billing#invoices'))}
                  />
                </YGroup.Item>
                <YGroup.Item>
                  <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} />}
                    onPress={() => navigate(ADMIN_DATA_EXPORTS_PATH)}
                  />
                </YGroup.Item>
              </>
            ) : null}
          </YGroup>
        </YStack>
      </Card>

      <Card
        borderRadius={22}
        borderWidth={2}
        borderColor={borderColor}
        backgroundColor={surface}
        padding="$3"
        shadowColor={shadow}
        shadowOpacity={0.16}
        shadowRadius={16}
        shadowOffset={{ width: 0, height: 10 }}
      >
        <YStack space="$2.5">
          <XStack
            alignItems="center"
            paddingHorizontal="$3"
            paddingVertical="$1.5"
            borderRadius={999}
            borderWidth={1}
            borderColor={borderColor}
            backgroundColor={surfaceMuted}
          >
            <Text fontSize="$xs" fontWeight="800" color={textColor}>
              {t('mobileProfile.preferences', 'Preferences')}
            </Text>
          </XStack>
          <YGroup {...({ borderRadius: "$4", borderWidth: 1, borderColor: borderColor, overflow: "hidden" } as any)}>
            <YGroup.Item>
              <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>
        </YStack>
      </Card>

      <Card
        borderRadius={22}
        borderWidth={2}
        borderColor={withAlpha(danger, 0.4)}
        backgroundColor={surface}
        padding="$3"
        shadowColor={shadow}
        shadowOpacity={0.12}
        shadowRadius={12}
        shadowOffset={{ width: 0, height: 6 }}
      >
        <YStack space="$2">
          <XStack alignItems="center" space="$2">
            <XStack
              width={36}
              height={36}
              borderRadius={12}
              alignItems="center"
              justifyContent="center"
              backgroundColor={withAlpha(danger, 0.12)}
            >
              <LogOut size={16} color={danger} />
            </XStack>
            <Text fontSize="$sm" fontWeight="800" color={textColor}>
              {t('mobileProfile.logoutTitle', 'Sign out')}
            </Text>
          </XStack>
          <Text fontSize="$xs" color={mutedText}>
            {t('mobileProfile.logoutHint', 'Sign out from this device.')}
          </Text>
          <CTAButton
            label={t('mobileProfile.logout', 'Log out')}
            tone="danger"
            onPress={() => {
              logout();
              navigate(adminPath('/logout'));
            }}
          />
        </YStack>
      </Card>
    </MobileShell>
  );
}
