import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';
import '../../widgets/backoffice_ui.dart';
import '../../widgets/drawer_shell.dart';

class DoctorSettingsPage extends ConsumerWidget {
  const DoctorSettingsPage({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        surfaceTintColor: Colors.transparent,
        title: const Text('设置', style: TextStyle(color: AppColors.textPrimary)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () => popRoute(ref),
        ),
      ),
      body: BackofficeSurface(
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            _SettingTile(
              Icons.notifications_outlined,
              '推送通知',
              trailing: Switch(value: true, onChanged: (_) {}),
            ),
            _SettingTile(
              Icons.description_outlined,
              '隐私政策',
              onTap: () {
                pushRoute(ref, 'staticText', params: {'type': 'privacy'});
              },
            ),
            _SettingTile(
              Icons.article_outlined,
              '用户协议',
              onTap: () {
                pushRoute(ref, 'staticText', params: {'type': 'terms'});
              },
            ),
            const SizedBox(height: 24),
            _SettingTile(
              Icons.delete_forever_outlined,
              '删除账号',
              color: Colors.red,
              onTap: () => _confirmDelete(context, ref),
            ),
            const SizedBox(height: 24),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () async {
                  final confirmed = await confirmAccountAction(
                    context,
                    title: '退出登录',
                    message: '确定退出当前医生账号吗？',
                    confirmLabel: '退出登录',
                  );
                  if (!confirmed || !context.mounted) return;
                  await ref.read(authProvider.notifier).logout();
                  goRoute(ref, 'login');
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.white,
                  foregroundColor: AppColors.error,
                  elevation: 0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(14),
                    side: const BorderSide(color: Color(0xFFFECACA)),
                  ),
                  padding: const EdgeInsets.symmetric(vertical: 14),
                ),
                child: const Text('退出登录'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _confirmDelete(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('删除账号'),
        content: const Text('此操作将永久删除你的所有数据，包括个人信息、问诊记录等。此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(ctx);
              try {
                await ref.read(apiClientProvider).delete('/api/user/account');
                await ref.read(authProvider.notifier).logout();
                if (context.mounted) goRoute(ref, 'login');
              } catch (_) {}
            },
            child: const Text('确认删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}

class _SettingTile extends StatelessWidget {
  final IconData icon;
  final String label;
  final Color? color;
  final Widget? trailing;
  final VoidCallback? onTap;
  const _SettingTile(
    this.icon,
    this.label, {
    this.color,
    this.trailing,
    this.onTap,
  });
  @override
  Widget build(BuildContext context) => Container(
    margin: const EdgeInsets.only(bottom: 8),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(14),
      border: Border.all(color: AppColors.border),
      boxShadow: AppColors.cardShadowLight,
    ),
    child: ListTile(
      leading: Icon(icon, color: color ?? AppColors.primary),
      title: Text(
        label,
        style: TextStyle(
          fontSize: 15,
          color: color ?? AppColors.textPrimary,
          fontWeight: FontWeight.w600,
        ),
      ),
      trailing:
          trailing ??
          (onTap != null
              ? const Icon(Icons.chevron_right, color: AppColors.textHint)
              : null),
      onTap: onTap,
    ),
  );
}
