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/data_providers.dart';
import '../../widgets/app_empty_state.dart';
import '../../widgets/app_future_view.dart';
import '../../widgets/app_status_badge.dart';
import '../../widgets/common_widgets.dart';
import '../../widgets/enterprise_widgets.dart';

class MedicationListPage extends ConsumerStatefulWidget {
  const MedicationListPage({super.key});
  @override
  ConsumerState<MedicationListPage> createState() => _MedicationListPageState();
}

class _MedicationListPageState extends ConsumerState<MedicationListPage> {
  static const _medVisual = AppModuleVisuals.medication;
  Future<List<Map<String, dynamic>>>? _future;

  @override
  void initState() {
    super.initState();
    _load();
  }

  void _load() {
    setState(() {
      _future = ref.read(medicationServiceProvider).getMedications('');
    });
  }

  Future<void> _delete(String id) async {
    await ref.read(medicationServiceProvider).deleteMedication(id);
    ref.invalidate(medicationListProvider);
    _load();
  }

  @override
  Widget build(BuildContext context) {
    return GradientScaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => popRoute(ref),
        ),
        title: const Text('用药管理'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => pushRoute(ref, 'medicationEdit'),
        backgroundColor: _medVisual.color,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: const Icon(Icons.add, size: 28, color: Colors.white),
      ),
      body: AppFutureView<List<Map<String, dynamic>>>(
        future: _future,
        onRetry: _load,
        errorTitle: '用药信息加载失败',
        onData: (ctx, list) {
          if (list.isEmpty) {
            return AppEmptyState(
              icon: _medVisual.icon,
              title: '暂无用药',
              subtitle: '点击右下角➕添加药品',
            );
          }
          final activeCount = list.where((m) => m['isActive'] == true).length;
          final reminderCount = list.where((m) {
            final times = m['timeOfDay'] as List?;
            return times != null && times.isNotEmpty;
          }).length;
          return ListView(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 88),
            children: [
              EnterpriseHeader(
                title: '今日用药概览',
                subtitle: '集中管理服药计划、剂量和每日打卡状态',
                icon: _medVisual.icon,
                color: _medVisual.color,
                accent: AppColors.primary,
                showIcon: false,
                stats: [
                  EnterpriseStat(
                    label: '药品总数',
                    value: '${list.length} 个',
                    icon: Icons.inventory_2_outlined,
                  ),
                  EnterpriseStat(
                    label: '服用中',
                    value: '$activeCount 个',
                    icon: Icons.check_circle_outline,
                  ),
                  EnterpriseStat(
                    label: '有提醒',
                    value: '$reminderCount 个',
                    icon: Icons.alarm_outlined,
                  ),
                ],
              ),
              const SizedBox(height: 10),
              _MedicationListGroup(
                children: List.generate(list.length, (i) {
                  final m = list[i];
                  final times =
                      (m['timeOfDay'] as List?)
                          ?.map((t) => t.toString().substring(0, 5))
                          .join(' ') ??
                      '';
                  final isActive = m['isActive'] == true;
                  final id = m['id']?.toString() ?? '';
                  return SwipeDeleteTile(
                    key: Key(id),
                    onDelete: () => _delete(id),
                    onTap: () =>
                        pushRoute(ref, 'medCheckIn', params: {'id': id}),
                    margin: EdgeInsets.zero,
                    child: _MedicationRow(
                      name: m['name']?.toString() ?? '',
                      subtitle: '${m['dosage'] ?? ''}  $times',
                      isActive: isActive,
                      showDivider: i < list.length - 1,
                      visual: _medVisual,
                    ),
                  );
                }),
              ),
            ],
          );
        },
      ),
    );
  }
}

class _MedicationListGroup extends StatelessWidget {
  final List<Widget> children;

  const _MedicationListGroup({required this.children});

  @override
  Widget build(BuildContext context) {
    return Container(
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: AppRadius.xlBorder,
      ),
      child: Column(children: children),
    );
  }
}

class _MedicationRow extends StatelessWidget {
  final String name;
  final String subtitle;
  final bool isActive;
  final bool showDivider;
  final AppModuleVisual visual;

  const _MedicationRow({
    required this.name,
    required this.subtitle,
    required this.isActive,
    required this.showDivider,
    required this.visual,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(
              horizontal: AppTheme.sLg,
              vertical: 13,
            ),
            child: Row(
              children: [
                Container(
                  width: 44,
                  height: 44,
                  decoration: BoxDecoration(
                    gradient: isActive
                        ? visual.gradient
                        : AppColors.surfaceGradient,
                    borderRadius: AppRadius.mdBorder,
                    border: Border.all(color: AppColors.borderLight),
                  ),
                  child: Icon(
                    visual.icon,
                    size: 25,
                    color: isActive ? Colors.white : AppTheme.textSub,
                  ),
                ),
                const SizedBox(width: AppTheme.sMd),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Flexible(
                            child: Text(
                              name,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: AppTextStyles.listTitle.copyWith(
                                color: isActive
                                    ? AppTheme.text
                                    : AppTheme.textSub,
                              ),
                            ),
                          ),
                          if (!isActive) ...[
                            const SizedBox(width: 6),
                            AppStatusBadge(label: '已停', color: visual.color),
                          ],
                        ],
                      ),
                      const SizedBox(height: 2),
                      Text(
                        subtitle,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: AppTextStyles.listSubtitle.copyWith(
                          color: AppTheme.textSub,
                        ),
                      ),
                    ],
                  ),
                ),
                const Icon(
                  Icons.chevron_right,
                  size: 21,
                  color: AppColors.textHint,
                ),
              ],
            ),
          ),
          if (showDivider)
            const Padding(
              padding: EdgeInsets.only(left: 74),
              child: Divider(
                height: 1,
                thickness: 0.7,
                color: Color(0xFFE8ECF2),
              ),
            ),
        ],
      ),
    );
  }
}
