import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_module_visuals.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(authProvider.select((state) => state.user));
    final name = user?.name?.trim().isNotEmpty == true ? user!.name! : '未设置昵称';
    final phone = user?.phone.trim().isNotEmpty == true
        ? user!.phone
        : '未绑定手机号';

    return GradientScaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 19),
          onPressed: () => popRoute(ref),
        ),
        title: const Text('个人信息'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: ListView(
          padding: const EdgeInsets.fromLTRB(18, 12, 18, 32),
          children: [
            _AccountSummary(
              name: name,
              phone: phone,
              avatarUrl: user?.avatarUrl,
            ),
            const SizedBox(height: 20),
            const _SectionTitle('资料管理'),
            const SizedBox(height: 9),
            _SettingsGroup(
              children: [
                _ActionRow(
                  icon: Icons.badge_outlined,
                  iconColor: AppColors.primary,
                  title: '基本资料',
                  subtitle: '姓名、性别和出生日期',
                  onTap: () => pushRoute(ref, 'profileEdit'),
                ),
                _ActionRow(
                  icon: AppModuleVisuals.health.icon,
                  iconColor: AppModuleVisuals.health.color,
                  title: '健康档案',
                  subtitle: '疾病、手术、过敏和生活习惯',
                  onTap: () => pushRoute(ref, 'healthArchive'),
                ),
              ],
            ),
            const SizedBox(height: 20),
            const _SectionTitle('账号操作'),
            const SizedBox(height: 9),
            _SettingsGroup(
              children: [
                _ActionRow(
                  icon: Icons.logout_rounded,
                  iconColor: AppColors.textSecondary,
                  title: '退出登录',
                  showChevron: false,
                  onTap: () => _logout(context, ref),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _logout(BuildContext context, WidgetRef ref) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (dialogContext) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: AppRadius.lgBorder),
        title: const Text('退出登录'),
        content: const Text('确定退出当前账号吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(dialogContext, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(dialogContext, true),
            style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
            child: const Text('退出'),
          ),
        ],
      ),
    );
    if (confirmed != true || !context.mounted) return;
    await ref.read(authProvider.notifier).logout();
    goRoute(ref, 'login');
  }
}

class _AccountSummary extends StatelessWidget {
  final String name;
  final String phone;
  final String? avatarUrl;

  const _AccountSummary({
    required this.name,
    required this.phone,
    required this.avatarUrl,
  });

  @override
  Widget build(BuildContext context) => Container(
    padding: const EdgeInsets.all(18),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: AppRadius.lgBorder,
    ),
    child: Row(
      children: [
        Container(
          width: 60,
          height: 60,
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            color: AppModuleVisuals.health.lightColor,
            borderRadius: AppRadius.lgBorder,
          ),
          child: avatarUrl?.isNotEmpty == true
              ? Image.network(
                  avatarUrl!,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) =>
                      const _AvatarFallback(),
                )
              : const _AvatarFallback(),
        ),
        const SizedBox(width: 15),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                name,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: AppTextStyles.summaryTitle.copyWith(fontSize: 20),
              ),
              const SizedBox(height: 5),
              Text(phone, style: AppTextStyles.listSubtitle),
              const SizedBox(height: 5),
              const Text(
                '头像由账号系统统一管理',
                style: TextStyle(fontSize: 12, color: AppColors.textHint),
              ),
            ],
          ),
        ),
      ],
    ),
  );
}

class _AvatarFallback extends StatelessWidget {
  const _AvatarFallback();

  @override
  Widget build(BuildContext context) => Icon(
    Icons.person_rounded,
    color: AppModuleVisuals.health.color,
    size: 34,
  );
}

class _SectionTitle extends StatelessWidget {
  final String text;
  const _SectionTitle(this.text);

  @override
  Widget build(BuildContext context) => Padding(
    padding: const EdgeInsets.symmetric(horizontal: 2),
    child: Text(
      text,
      style: const TextStyle(
        fontSize: 15,
        fontWeight: FontWeight.w600,
        color: AppColors.textSecondary,
      ),
    ),
  );
}

class _SettingsGroup extends StatelessWidget {
  final List<Widget> children;
  const _SettingsGroup({required this.children});

  @override
  Widget build(BuildContext context) => Container(
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: AppRadius.lgBorder,
    ),
    child: Column(
      children: [
        for (var i = 0; i < children.length; i++) ...[
          children[i],
          if (i != children.length - 1)
            const Padding(
              padding: EdgeInsets.only(left: 62),
              child: Divider(height: 1, color: AppColors.borderLight),
            ),
        ],
      ],
    ),
  );
}

class _ActionRow extends StatelessWidget {
  final IconData icon;
  final Color iconColor;
  final String title;
  final String? subtitle;
  final bool showChevron;
  final VoidCallback onTap;

  const _ActionRow({
    required this.icon,
    required this.iconColor,
    required this.title,
    this.subtitle,
    this.showChevron = true,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) => Material(
    color: Colors.transparent,
    child: InkWell(
      onTap: onTap,
      borderRadius: AppRadius.lgBorder,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 14),
        child: Row(
          children: [
            Container(
              width: 36,
              height: 36,
              decoration: BoxDecoration(
                color: iconColor.withValues(alpha: 0.10),
                borderRadius: AppRadius.smBorder,
              ),
              child: Icon(icon, color: iconColor, size: 20),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  if (subtitle != null) ...[
                    const SizedBox(height: 3),
                    Text(subtitle!, style: AppTextStyles.listSubtitle),
                  ],
                ],
              ),
            ),
            if (showChevron)
              const Icon(
                Icons.chevron_right_rounded,
                color: AppColors.textHint,
              ),
          ],
        ),
      ),
    ),
  );
}
