import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.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/common_widgets.dart';

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

class _MedicationListPageState extends ConsumerState<MedicationListPage>
    with SingleTickerProviderStateMixin {
  String _filter = '';
  Future<List<Map<String, dynamic>>>? _future;
  late final _tabCtrl = TabController(length: 3, vsync: this);

  @override
  void initState() {
    super.initState();
    _tabCtrl.addListener(() {
      if (!_tabCtrl.indexIsChanging) {
        setState(() {
          _filter = ['', 'active', 'inactive'][_tabCtrl.index];
        });
        _load();
      }
    });
    _load();
  }

  @override
  void dispose() {
    _tabCtrl.dispose();
    super.dispose();
  }

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

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

  static const _tabs = ['全部', '服用中', '已停药'];

  @override
  Widget build(BuildContext context) {
    return GradientScaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => popRoute(ref),
        ),
        title: const Text('用药管理'),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(48),
          child: TabBar(
            controller: _tabCtrl,
            indicatorColor: AppColors.primary,
            labelColor: AppColors.primary,
            unselectedLabelColor: AppColors.textHint,
            labelStyle: const TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w600,
            ),
            tabs: _tabs.map((t) => Tab(child: Text(t))).toList(),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => pushRoute(ref, 'medicationEdit'),
        backgroundColor: AppColors.primaryDark,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: const Icon(Icons.add, size: 28, color: Colors.white),
      ),
      body: Container(
        decoration: const BoxDecoration(gradient: AppColors.bgGradient),
        child: AppFutureView<List<Map<String, dynamic>>>(
          future: _future,
          onRetry: _load,
          errorTitle: '用药信息加载失败',
          onData: (ctx, list) {
            if (list.isEmpty) {
              return const AppEmptyState(
                icon: Icons.medication_outlined,
                title: '暂无用药',
                subtitle: '点击右下角➕添加药品',
              );
            }
            return ListView.builder(
              padding: const EdgeInsets.fromLTRB(0, 8, 0, 80),
              itemCount: list.length,
              itemBuilder: (ctx, 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: const EdgeInsets.symmetric(
                    horizontal: AppTheme.sLg,
                    vertical: 4,
                  ),
                  child: Container(
                    padding: const EdgeInsets.all(AppTheme.sLg),
                    decoration: BoxDecoration(
                      gradient: AppColors.surfaceGradient,
                      borderRadius: BorderRadius.circular(AppTheme.rLg),
                      border: Border.all(color: AppColors.borderLight),
                      boxShadow: AppColors.cardShadowLight,
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: 44,
                          height: 44,
                          decoration: BoxDecoration(
                            gradient: isActive
                                ? AppColors.primaryGradient
                                : AppColors.surfaceGradient,
                            borderRadius: BorderRadius.circular(AppTheme.rMd),
                            border: Border.all(color: AppColors.borderLight),
                          ),
                          child: Icon(
                            Icons.medication_outlined,
                            size: 25,
                            color: isActive ? Colors.white : AppTheme.textSub,
                          ),
                        ),
                        const SizedBox(width: AppTheme.sMd),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Text(
                                    m['name']?.toString() ?? '',
                                    style: TextStyle(
                                      fontSize: 19,
                                      fontWeight: FontWeight.w600,
                                      color: isActive
                                          ? AppTheme.text
                                          : AppTheme.textSub,
                                    ),
                                  ),
                                  if (!isActive) ...[
                                    const SizedBox(width: 6),
                                    Container(
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 6,
                                        vertical: 1,
                                      ),
                                      decoration: BoxDecoration(
                                        color: AppTheme.bgSoft,
                                        borderRadius: BorderRadius.circular(4),
                                      ),
                                      child: Text(
                                        '已停',
                                        style: TextStyle(
                                          fontSize: 13,
                                          color: AppTheme.textSub,
                                        ),
                                      ),
                                    ),
                                  ],
                                ],
                              ),
                              const SizedBox(height: 2),
                              Text(
                                '${m['dosage'] ?? ''}  $times',
                                style: TextStyle(
                                  fontSize: 16,
                                  color: AppTheme.textSub,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Icon(
                          Icons.chevron_right,
                          size: 21,
                          color: AppTheme.border,
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}
