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 auth = ref.watch(authProvider);
    final user = auth.user;
    final name = user?.name?.isNotEmpty == true ? user!.name! : '未设置昵称';
    final phone = 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, 16, 18, 32),
          children: [
            _AccountCard(
              name: name,
              phone: phone.isNotEmpty ? phone : '未绑定手机号',
              avatarUrl: user?.avatarUrl,
            ),
            const SizedBox(height: 14),
            _ActionTile(
              icon: AppModuleVisuals.health.icon,
              title: '健康档案',
              subtitle: '维护个人资料、病史、手术和过敏信息',
              visual: AppModuleVisuals.health,
              onTap: () => pushRoute(ref, 'healthArchive'),
            ),
            const SizedBox(height: 14),
            _LogoutButton(onPressed: () => _logout(context, ref)),
          ],
        ),
      ),
    );
  }

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

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

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

  @override
  Widget build(BuildContext context) => Container(
    padding: AppSpacing.panel,
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: AppRadius.lgBorder,
      border: Border.all(color: AppColors.border, width: 1.1),
      boxShadow: AppShadows.soft,
    ),
    child: Row(
      children: [
        _Avatar(avatarUrl: avatarUrl),
        const SizedBox(width: 14),
        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,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: AppTextStyles.listSubtitle,
              ),
            ],
          ),
        ),
      ],
    ),
  );
}

class _Avatar extends StatelessWidget {
  final String? avatarUrl;

  const _Avatar({required this.avatarUrl});

  @override
  Widget build(BuildContext context) => Container(
    width: 58,
    height: 58,
    decoration: BoxDecoration(
      gradient: AppModuleVisuals.health.gradient,
      borderRadius: AppRadius.lgBorder,
    ),
    clipBehavior: Clip.antiAlias,
    child: avatarUrl != null && avatarUrl!.isNotEmpty
        ? Image.network(avatarUrl!, fit: BoxFit.cover)
        : const Icon(Icons.person_rounded, color: Colors.white, size: 34),
  );
}

class _ActionTile extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final AppModuleVisual visual;
  final VoidCallback onTap;

  const _ActionTile({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.visual,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) => Material(
    color: Colors.white,
    borderRadius: AppRadius.lgBorder,
    child: InkWell(
      onTap: onTap,
      borderRadius: AppRadius.lgBorder,
      child: Container(
        padding: const EdgeInsets.all(15),
        decoration: BoxDecoration(
          borderRadius: AppRadius.lgBorder,
          border: Border.all(color: AppColors.border, width: 1.1),
          boxShadow: AppShadows.soft,
        ),
        child: Row(
          children: [
            Container(
              width: 46,
              height: 46,
              decoration: BoxDecoration(
                gradient: visual.gradient,
                borderRadius: AppRadius.mdBorder,
              ),
              child: Icon(icon, color: Colors.white, size: 24),
            ),
            const SizedBox(width: 13),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: AppTextStyles.listTitle),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: AppTextStyles.listSubtitle,
                  ),
                ],
              ),
            ),
            const Icon(Icons.chevron_right_rounded, color: AppColors.textHint),
          ],
        ),
      ),
    ),
  );
}

class _LogoutButton extends StatelessWidget {
  final VoidCallback onPressed;

  const _LogoutButton({required this.onPressed});

  @override
  Widget build(BuildContext context) => TextButton(
    onPressed: onPressed,
    style: TextButton.styleFrom(
      foregroundColor: AppColors.error,
      padding: const EdgeInsets.symmetric(vertical: 14),
      textStyle: AppTextStyles.button,
    ),
    child: const Text('退出登录'),
  );
}
