import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../../core/i18n/app_localizations.dart';
import '../../core/i18n/locale_provider.dart';
import '../../core/theme/theme_mode_provider.dart';
import '../../core/auth/role_provider.dart';
import '../../shared/widgets/profile_menu_item.dart';
import '../../shared/widgets/nav_bar_config.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_colors_extension.dart';

class ProfilePage extends ConsumerWidget {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final l10n = AppLocalizations.of(context);
    final location = GoRouterState.of(context).uri.toString();
    final currentLocale = ref.watch(localeProvider);
    final themeMode = ref.watch(themeModeProvider);
    final isDark = themeMode == ThemeMode.dark;
    final currentRole = ref.watch(currentRoleProvider);
    final isAdmin = currentRole == 'admin';

    if (location.startsWith('/profile')) {
      ref
          .read(navBarConfigProvider.notifier)
          .update(
            NavBarConfig(
              title: l10n.get('tabProfile'),
              showBack: true,
              leadingIcon: Icons.close,
            ),
          );
    }
    return SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: Column(
        children: [
          const SizedBox(height: 16),
          _buildUserInfoCard(context, l10n),
          const SizedBox(height: 16),
          // 功能列表
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              children: [
                // ── 角色切换（测试用）──
                ProfileMenuItem(
                  icon: Icons.people,
                  label: '角色切换',
                  trailing: _roleName(currentRole),
                  onTap: () => _showRoleSheet(context, ref, currentRole),
                ),
                const SizedBox(height: 8),
                // ── 语言设置 ──
                ProfileMenuItem(
                  icon: Icons.language,
                  label: l10n.get('language'),
                  trailing: _localeName(currentLocale),
                  onTap: () => _showLanguageSheet(context, ref, currentLocale),
                ),
                const SizedBox(height: 8),
                // ── 深色模式 ──
                ProfileMenuItem(
                  icon: Icons.dark_mode,
                  label: l10n.get('darkMode'),
                  trailingWidget: TDSwitch(
                    isOn: isDark,
                    onChanged: (v) {
                      ref.read(themeModeProvider.notifier).toggle();
                      return v;
                    },
                  ),
                ),
                const SizedBox(height: 8),
                if (isAdmin) ...[
                  ProfileMenuItem(
                    icon: Icons.admin_panel_settings,
                    label: '权限管理',
                    onTap: () => context.push('/admin/permissions'),
                  ),
                  const SizedBox(height: 8),
                ],
                // ── 关于 ──
                ProfileMenuItem(
                  icon: Icons.info_outline,
                  label: l10n.get('about'),
                  onTap: () => _showAboutDialog(context, l10n),
                ),
              ],
            ),
          ),
          const SizedBox(height: 8),
          TDFooter(TDFooterType.text, text: l10n.get('version')),
        ],
      ),
    );
  }

  Widget _buildUserInfoCard(BuildContext context, AppLocalizations l10n) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
      decoration: BoxDecoration(
        color: colors.bgCard,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          // 头像 - 点击更换占位
          GestureDetector(
            onTap: () {
              TDToast.showText(
                '头像更换功能（占位）',
                context: context,
                duration: Duration(seconds: 2),
              );
            },
            child: Container(
              width: 64,
              height: 64,
              decoration: BoxDecoration(
                color: colors.primaryLight,
                shape: BoxShape.circle,
              ),
              child: Center(
                child: Text(
                  '张',
                  style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.w700,
                    color: colors.primary,
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(width: 16),
          // 用户信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  l10n.get('userName'),
                  style: TextStyle(
                    fontSize: AppFontSizes.title,
                    fontWeight: FontWeight.w600,
                    color: colors.textPrimary,
                  ),
                ),
                const SizedBox(height: AppSpacing.xs),
                Text(
                  l10n.get('salesDepartment'),
                  style: TextStyle(
                    fontSize: AppFontSizes.body,
                    color: colors.textSecondary,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  '销售经理',
                  style: TextStyle(fontSize: 12, color: colors.textPlaceholder),
                ),
              ],
            ),
          ),
          // 箭头
          Icon(Icons.chevron_right, size: 16, color: colors.textPlaceholder),
        ],
      ),
    );
  }

  String _localeName(Locale locale) {
    if (locale.languageCode == 'zh' && locale.countryCode == 'TW') {
      return '繁體中文';
    }
    if (locale.languageCode == 'en') {
      return 'English';
    }
    return '简体中文';
  }

  String _roleName(String role) {
    for (final (value, label) in roleOptions) {
      if (value == role) return label;
    }
    return role;
  }

  void _showRoleSheet(
    BuildContext context,
    WidgetRef ref,
    String currentRole,
  ) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;

    TDActionSheet.showListActionSheet(
      context,
      showCancel: false,
      useSafeArea: false,
      items: roleOptions.map((r) {
        final isSelected = r.$1 == currentRole;
        return TDActionSheetItem(
          label: isSelected ? '${r.$2}  ✓' : r.$2,
          textStyle: TextStyle(
            color: isSelected ? colors.primary : colors.textPrimary,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
          ),
        );
      }).toList(),
      onSelected: (item, index) {
        ref.read(currentRoleProvider.notifier).state = roleOptions[index].$1;
      },
    );
  }

  void _showLanguageSheet(
    BuildContext context,
    WidgetRef ref,
    Locale currentLocale,
  ) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final languages = [
      (label: '简体中文', locale: const Locale('zh', 'CN')),
      (label: 'English', locale: const Locale('en')),
      (label: '繁體中文', locale: const Locale('zh', 'TW')),
    ];

    TDActionSheet.showListActionSheet(
      context,
      showCancel: false,
      useSafeArea: false,
      items: languages.map((lang) {
        final isSelected =
            lang.locale.languageCode == currentLocale.languageCode &&
            lang.locale.countryCode == currentLocale.countryCode;
        return TDActionSheetItem(
          label: isSelected ? '${lang.label}  ✓' : lang.label,
          textStyle: TextStyle(
            color: isSelected ? colors.primary : colors.textPrimary,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
          ),
        );
      }).toList(),
      onSelected: (item, index) {
        ref.read(localeProvider.notifier).setLocale(languages[index].locale);
      },
    );
  }

  void _showAboutDialog(BuildContext context, AppLocalizations l10n) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    showGeneralDialog(
      context: context,
      pageBuilder:
          (
            BuildContext buildContext,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) {
            return TDConfirmDialog(
              title: l10n.get('about'),
              titleColor: colors.textPrimary,
              contentWidget: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _aboutRow(
                    l10n.get('version'),
                    'v1.0.0 (Build 20260601)',
                    colors,
                  ),
                  const Divider(height: 24),
                  GestureDetector(
                    onTap: () {
                      Navigator.of(buildContext).pop();
                      TDToast.showText(
                        '用户协议（占位）',
                        context: context,
                        duration: Duration(seconds: 2),
                      );
                    },
                    child: Text(
                      '用户协议',
                      style: TextStyle(fontSize: 14, color: colors.primary),
                    ),
                  ),
                  const SizedBox(height: 12),
                  GestureDetector(
                    onTap: () {
                      Navigator.of(buildContext).pop();
                      TDToast.showText(
                        '隐私政策（占位）',
                        context: context,
                        duration: Duration(seconds: 2),
                      );
                    },
                    child: Text(
                      '隐私政策',
                      style: TextStyle(fontSize: 14, color: colors.primary),
                    ),
                  ),
                ],
              ),
              buttonStyle: TDDialogButtonStyle.text,
              buttonText: l10n.get('close'),
              buttonTextColor: colors.primary,
              action: () => Navigator.of(buildContext).pop(),
            );
          },
    );
  }

  Widget _aboutRow(String label, String value, AppColorsExtension colors) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(fontSize: 14, color: colors.textSecondary),
        ),
        Flexible(
          child: Text(
            value,
            textAlign: TextAlign.right,
            softWrap: true,
            style: TextStyle(fontSize: 14, color: colors.textPrimary),
          ),
        ),
      ],
    );
  }
}
