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

import '../../core/api_client.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_toast.dart';
import '../../widgets/common_widgets.dart';
import '../care_plan_ui_logic.dart';
import 'medication_ui_logic.dart';

class MedicationListPage extends ConsumerStatefulWidget {
  const MedicationListPage({super.key});

  @override
  ConsumerState<MedicationListPage> createState() => _MedicationListPageState();
}

class _MedicationListPageState extends ConsumerState<MedicationListPage> {
  final Set<String> _deleting = {};

  Future<void> _refresh() => ref.refresh(medicationListProvider.future);

  Future<void> _confirmDelete(String id, String name) async {
    if (id.isEmpty || _deleting.contains(id)) return;
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: const Text('删除用药'),
        content: Text('确定删除“$name”吗？相关服药记录也将一并删除。'),
        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 || !mounted) return;
    setState(() => _deleting.add(id));
    try {
      await ref.read(medicationServiceProvider).deleteMedication(id);
      ref.invalidate(medicationListProvider);
      ref.invalidate(medicationReminderProvider);
      if (mounted) AppToast.show(context, '用药已删除', type: AppToastType.success);
    } catch (error) {
      if (mounted) {
        AppToast.show(
          context,
          error is ApiException ? error.message : '删除失败，请稍后重试',
          type: AppToastType.error,
        );
      }
    } finally {
      if (mounted) setState(() => _deleting.remove(id));
    }
  }

  @override
  Widget build(BuildContext context) {
    return GradientScaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => popRoute(ref),
        ),
        title: const Text('用药管理'),
      ),
      floatingActionButton: AppCreateFab(
        tooltip: '添加用药',
        onPressed: () => pushRoute(ref, 'medicationEdit'),
      ),
      body: AppAsyncValueView<List<Map<String, dynamic>>>(
        value: ref.watch(medicationListProvider),
        onRetry: () => ref.invalidate(medicationListProvider),
        errorTitle: '用药信息加载失败',
        onData: (_, medications) {
          if (medications.isEmpty) {
            return AppEmptyState(
              icon: AppModuleVisuals.medication.icon,
              title: '暂无用药',
              subtitle: '点击右下角添加药品',
              iconColor: AppColors.medication,
            );
          }
          final groups = <CarePlanPhase, List<Map<String, dynamic>>>{
            for (final phase in CarePlanPhase.values) phase: [],
          };
          for (final medication in medications) {
            final phase = resolveCarePlanPhase(
              enabled: medication['isActive'] == true,
              startDate: medication['startDate']?.toString(),
              endDate: medication['endDate']?.toString(),
            );
            groups[phase]!.add(medication);
          }
          final active = groups[CarePlanPhase.active]!;
          final doseCount = active.fold<int>(
            0,
            (sum, item) => sum + ((item['timeOfDay'] as List?)?.length ?? 0),
          );
          return RefreshIndicator(
            onRefresh: _refresh,
            child: ListView(
              physics: const AlwaysScrollableScrollPhysics(),
              padding: AppSpacing.pageWithFab,
              children: [
                _MedicationOverview(
                  activeCount: active.length,
                  doseCount: doseCount,
                  nextReminder: _nextReminder(active),
                ),
                const SizedBox(height: 18),
                for (final phase in CarePlanPhase.values)
                  if (groups[phase]!.isNotEmpty) ...[
                    _MedicationPhaseGroup(
                      phase: phase,
                      medications: groups[phase]!,
                      deleting: _deleting,
                      onOpen: (id) =>
                          pushRoute(ref, 'medCheckIn', params: {'id': id}),
                      onEdit: (id) =>
                          pushRoute(ref, 'medicationEdit', params: {'id': id}),
                      onDelete: _confirmDelete,
                    ),
                    const SizedBox(height: 18),
                  ],
              ],
            ),
          );
        },
      ),
    );
  }
}

class _MedicationOverview extends StatelessWidget {
  final int activeCount;
  final int doseCount;
  final String? nextReminder;

  const _MedicationOverview({
    required this.activeCount,
    required this.doseCount,
    required this.nextReminder,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: AppSpacing.panel,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: AppRadius.lgBorder,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Expanded(
                child: Text('用药概览', style: AppTextStyles.sectionTitle),
              ),
              Text(
                nextReminder == null ? '今日已无待服' : '下次 $nextReminder',
                style: AppTextStyles.listSubtitle.copyWith(
                  color: nextReminder == null
                      ? AppColors.successText
                      : AppColors.textSecondary,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _OverviewValue(
                  value: '$activeCount种',
                  label: '正在服用',
                  color: AppColors.textPrimary,
                ),
              ),
              Container(width: 1, height: 46, color: AppColors.divider),
              Expanded(
                child: _OverviewValue(
                  value: '$doseCount次',
                  label: '今日安排',
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _OverviewValue extends StatelessWidget {
  final String value;
  final String label;
  final Color color;

  const _OverviewValue({
    required this.value,
    required this.label,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(value, style: AppTextStyles.summaryTitle.copyWith(color: color)),
        const SizedBox(height: 2),
        Text(label, style: AppTextStyles.listSubtitle.copyWith(fontSize: 13)),
      ],
    );
  }
}

class _MedicationPhaseGroup extends StatelessWidget {
  final CarePlanPhase phase;
  final List<Map<String, dynamic>> medications;
  final Set<String> deleting;
  final ValueChanged<String> onOpen;
  final ValueChanged<String> onEdit;
  final Future<void> Function(String, String) onDelete;

  const _MedicationPhaseGroup({
    required this.phase,
    required this.medications,
    required this.deleting,
    required this.onOpen,
    required this.onEdit,
    required this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    final color = _phaseColor(phase);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 2, bottom: 9),
          child: Row(
            children: [
              Container(
                width: 8,
                height: 8,
                decoration: BoxDecoration(color: color, shape: BoxShape.circle),
              ),
              const SizedBox(width: 8),
              Text(
                '${_phaseLabel(phase)}（${medications.length}）',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: color,
                ),
              ),
            ],
          ),
        ),
        Container(
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: AppRadius.lgBorder,
          ),
          child: Column(
            children: List.generate(medications.length, (index) {
              final medication = medications[index];
              final id = medication['id']?.toString() ?? '';
              final name =
                  medication['name']?.toString().trim().isNotEmpty == true
                  ? medication['name'].toString().trim()
                  : '未命名药品';
              final isDeleting = deleting.contains(id);
              return SwipeDeleteTile(
                key: ValueKey(id),
                margin: EdgeInsets.zero,
                borderRadius: BorderRadius.zero,
                enabled: !isDeleting,
                onDelete: () => onDelete(id, name),
                child: _MedicationRow(
                  medication: medication,
                  phase: phase,
                  deleting: isDeleting,
                  showDivider: index < medications.length - 1,
                  onOpen: () => onOpen(id),
                  onEdit: () => onEdit(id),
                ),
              );
            }),
          ),
        ),
      ],
    );
  }
}

class _MedicationRow extends StatelessWidget {
  final Map<String, dynamic> medication;
  final CarePlanPhase phase;
  final bool deleting;
  final bool showDivider;
  final VoidCallback onOpen;
  final VoidCallback onEdit;

  const _MedicationRow({
    required this.medication,
    required this.phase,
    required this.deleting,
    required this.showDivider,
    required this.onOpen,
    required this.onEdit,
  });

  @override
  Widget build(BuildContext context) {
    final name = medication['name']?.toString() ?? '未命名药品';
    final dosage = medication['dosage']?.toString().trim() ?? '';
    final times =
        (medication['timeOfDay'] as List?)
            ?.map((time) => _formatTime(time.toString()))
            .join('、') ??
        '';
    return InkWell(
      onTap: deleting ? null : onOpen,
      child: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 12, 6, 12),
            child: Row(
              children: [
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: _phaseColor(phase).withValues(alpha: 0.10),
                    borderRadius: AppRadius.smBorder,
                  ),
                  child: Icon(
                    AppModuleVisuals.medication.icon,
                    color: _phaseColor(phase),
                    size: 22,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Flexible(
                            child: Text(
                              name,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: AppTextStyles.listTitle.copyWith(
                                fontSize: 17,
                              ),
                            ),
                          ),
                          if (dosage.isNotEmpty) ...[
                            const SizedBox(width: 8),
                            Text(dosage, style: AppTextStyles.tag),
                          ],
                        ],
                      ),
                      const SizedBox(height: 3),
                      Text(
                        times.isEmpty ? '未设置服药时间' : times,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: AppTextStyles.listSubtitle.copyWith(
                          fontSize: 13,
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        _periodText(medication),
                        style: AppTextStyles.listSubtitle.copyWith(
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
                if (deleting)
                  const Padding(
                    padding: EdgeInsets.all(12),
                    child: SizedBox(
                      width: 18,
                      height: 18,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    ),
                  )
                else
                  IconButton(
                    tooltip: '编辑用药',
                    onPressed: onEdit,
                    icon: const Icon(
                      LucideIcons.pencil,
                      size: 21,
                      color: AppColors.textSecondary,
                    ),
                  ),
              ],
            ),
          ),
          if (showDivider)
            const Positioned(
              left: 68,
              right: 0,
              bottom: 0,
              child: Divider(
                height: 1,
                thickness: 0.7,
                color: AppColors.divider,
              ),
            ),
        ],
      ),
    );
  }
}

String? _nextReminder(List<Map<String, dynamic>> medications) {
  final now = TimeOfDay.now();
  final nowMinutes = now.hour * 60 + now.minute;
  final times =
      medications
          .expand((item) => (item['timeOfDay'] as List?) ?? const [])
          .map((value) => _formatTime(value.toString()))
          .where((value) => value.length == 5)
          .toList()
        ..sort();
  for (final time in times) {
    final parts = time.split(':');
    final minutes =
        (int.tryParse(parts[0]) ?? 0) * 60 + (int.tryParse(parts[1]) ?? 0);
    if (minutes >= nowMinutes) return time;
  }
  return null;
}

String _periodText(Map<String, dynamic> medication) {
  return formatMedicationPeriod(medication['startDate'], medication['endDate']);
}

String _formatTime(String raw) => raw.length >= 5 ? raw.substring(0, 5) : raw;

String _phaseLabel(CarePlanPhase phase) => switch (phase) {
  CarePlanPhase.active => '正在服用',
  CarePlanPhase.upcoming => '即将开始',
  CarePlanPhase.ended => '已结束',
};

Color _phaseColor(CarePlanPhase phase) => switch (phase) {
  CarePlanPhase.active => AppColors.successText,
  CarePlanPhase.upcoming => AppColors.blueMeasure,
  CarePlanPhase.ended => AppColors.textHint,
};
