import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/navigation_provider.dart';
import '../../providers/data_providers.dart';

class MedicationListPage extends ConsumerStatefulWidget {
  const MedicationListPage({super.key});
  @override ConsumerState<MedicationListPage> createState() => _MedicationListPageState();
}
class _MedicationListPageState extends ConsumerState<MedicationListPage> {
  String _filter = '';
  Future<List<Map<String, dynamic>>>? _future;
  @override void initState() { super.initState(); _load(); }
  void _load() { setState(() { _future = ref.read(medicationServiceProvider).getMedications(_filter); }); }

  Future<void> _checkIn(String id) async {
    await ref.read(medicationServiceProvider).confirm(id);
    ref.invalidate(medicationReminderProvider);
    _load();
  }
  Future<void> _delete(String id) async {
    await ref.read(medicationServiceProvider).deleteMedication(id);
    _load();
  }
  Future<void> _toggleActive(Map<String, dynamic> m) async {
    await ref.read(medicationServiceProvider).update(m['id']?.toString() ?? '', {'isActive': !(m['isActive'] == true), 'name': m['name'] ?? '', 'dosage': m['dosage'] ?? '', 'frequency': 'Daily'});
    _load();
  }

  void _showDetail(Map<String, dynamic> m) {
    final times = (m['timeOfDay'] as List?)?.map((t) => t.toString().substring(0, 5)).join('、') ?? '';
    final isActive = m['isActive'] == true;
    showModalBottomSheet(context: context, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20))), builder: (ctx) => Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisSize: MainAxisSize.min, children: [
      Row(children: [
        Container(width: 48, height: 48, decoration: BoxDecoration(color: isActive ? const Color(0xFFEDEAFF) : const Color(0xFFF5F5F5), borderRadius: BorderRadius.circular(14)), child: Icon(Icons.medication_outlined, size: 24, color: isActive ? const Color(0xFF6C5CE7) : Colors.grey)),
        const SizedBox(width: 14),
        Expanded(child: Text(m['name']?.toString() ?? '', style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w700))),
        if (!isActive) const Text('  (已停用)', style: TextStyle(color: Color(0xFF999999))),
      ]),
      const SizedBox(height: 16),
      if (m['dosage']?.toString().isNotEmpty == true) _dRow(ctx, '剂量', m['dosage'].toString()),
      _dRow(ctx, '服用时间', times),
      _dRow(ctx, '频率', '每天${(m['timeOfDay'] as List?)?.length ?? 0}次'),
      if (m['startDate'] != null) _dRow(ctx, '开始', m['startDate'].toString().substring(0, 10)),
      if (m['endDate'] != null) _dRow(ctx, '结束', m['endDate'].toString().substring(0, 10)),
      if (m['notes']?.toString().isNotEmpty == true) _dRow(ctx, '备注', m['notes'].toString()),
      const SizedBox(height: 20),
      Row(children: [
        Expanded(child: OutlinedButton(onPressed: () { Navigator.pop(ctx); pushRoute(ref, 'medicationEdit', params: {'id': m['id']?.toString() ?? ''}); }, child: const Text('编辑'))),
        const SizedBox(width: 12),
        Expanded(child: OutlinedButton(onPressed: () { Navigator.pop(ctx); _toggleActive(m); }, child: Text(isActive ? '停药' : '恢复服用'), style: OutlinedButton.styleFrom(foregroundColor: isActive ? const Color(0xFFFF9800) : const Color(0xFF43A047)))),
      ]),
      const SizedBox(height: 8),
    ])));
  }

  Widget _dRow(BuildContext ctx, String label, String value) => Padding(padding: const EdgeInsets.only(bottom: 8), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
    SizedBox(width: 72, child: Text(label, style: const TextStyle(fontSize: 14, color: Color(0xFF888888)))),
    Expanded(child: Text(value, style: const TextStyle(fontSize: 14))),
  ]));

  @override Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FC),
      appBar: AppBar(title: const Text('用药管理'), actions: [
        TextButton(onPressed: () { pushRoute(ref, 'medicationEdit'); }, child: const Text('添加', style: TextStyle(fontSize: 15, color: Color(0xFF6C5CE7)))),
      ]),
      body: Column(children: [
        Padding(padding: const EdgeInsets.all(12), child: Row(children: [
          _tab('全部', ''), _tab('服用中', 'active'), _tab('已停药', 'inactive'),
        ])),
        Expanded(child: FutureBuilder<List<Map<String, dynamic>>>(
          future: _future,
          builder: (ctx, snap) {
            final list = snap.data ?? [];
            if (list.isEmpty) return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
              Icon(Icons.medication_outlined, size: 64, color: Colors.grey[300]),
              const SizedBox(height: 12), Text('暂无用药', style: TextStyle(color: Colors.grey[500])),
            ]));
            return ListView.builder(padding: const EdgeInsets.fromLTRB(0, 0, 0, 12), itemCount: list.length + 1, itemBuilder: (ctx, i) {
              if (i == list.length) return const SizedBox(height: 80);
              final m = list[i];
              final times = (m['timeOfDay'] as List?)?.map((t) => t.toString().substring(0, 5)).join(' ') ?? '';
              final todayTaken = m['todayTaken'] == true;
              final isActive = m['isActive'] == true;
              return _SwipeDeleteTile(
                key: Key(m['id']?.toString() ?? '$i'),
                onDelete: () => _delete(m['id']?.toString() ?? ''),
                onTap: () => _showDetail(m),
                child: Container(
                  margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
                  child: Row(children: [
                    Container(width: 44, height: 44, decoration: BoxDecoration(color: isActive ? const Color(0xFFEDEAFF) : const Color(0xFFF5F5F5), borderRadius: BorderRadius.circular(12)), child: Icon(Icons.medication_outlined, size: 22, color: isActive ? const Color(0xFF6C5CE7) : Colors.grey)),
                    const SizedBox(width: 12),
                    Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Row(children: [
                        Text(m['name']?.toString() ?? '', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: isActive ? const Color(0xFF1A1A1A) : Colors.grey)),
                        if (!isActive) ...[const SizedBox(width: 6), Container(padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), decoration: BoxDecoration(color: Colors.grey[200], borderRadius: BorderRadius.circular(4)), child: const Text('已停', style: TextStyle(fontSize: 10, color: Color(0xFF999999))))],
                      ]),
                      const SizedBox(height: 2),
                      Text('${m['dosage'] ?? ''}  $times', style: const TextStyle(fontSize: 13, color: Color(0xFF888888))),
                      if (m['notes']?.toString().isNotEmpty == true)
                        Text(m['notes'].toString(), style: const TextStyle(fontSize: 12, color: Color(0xFFBBBBBB)), maxLines: 1, overflow: TextOverflow.ellipsis),
                    ])),
                    if (isActive) GestureDetector(
                      onTap: () => _checkIn(m['id']?.toString() ?? ''),
                      child: Container(width: 40, height: 40,
                        decoration: BoxDecoration(color: todayTaken ? const Color(0xFFDCFCE7) : const Color(0xFFEDEAFF), borderRadius: BorderRadius.circular(12)),
                        child: Icon(todayTaken ? Icons.check_circle : Icons.check_circle_outline, size: 24, color: todayTaken ? const Color(0xFF43A047) : const Color(0xFFBBBBBB)),
                      ),
                    ),
                  ]),
                ),
              );
            });
          },
        )),
      ]),
    );
  }

  Widget _tab(String label, String value) {
    final sel = _filter == value;
    return GestureDetector(onTap: () { _filter = value; _load(); },
      child: Container(margin: const EdgeInsets.only(right: 8), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
        decoration: BoxDecoration(color: sel ? const Color(0xFF6C5CE7) : const Color(0xFFEDEAFF), borderRadius: BorderRadius.circular(16)),
        child: Text(label, style: TextStyle(fontSize: 13, color: sel ? Colors.white : const Color(0xFF6C5CE7), fontWeight: FontWeight.w500))),
    );
  }
}

class _SwipeDeleteTile extends StatefulWidget {
  final Widget child; final VoidCallback onDelete; final VoidCallback onTap;
  const _SwipeDeleteTile({super.key, required this.child, required this.onDelete, required this.onTap});
  @override State<_SwipeDeleteTile> createState() => _SwipeDeleteTileState();
}
class _SwipeDeleteTileState extends State<_SwipeDeleteTile> with SingleTickerProviderStateMixin {
  double _dx = 0; static const _max = 80.0, _threshold = 40.0;
  void _onUpdate(DragUpdateDetails d) => setState(() => _dx = (_dx + d.delta.dx).clamp(-_max, 0.0));
  void _onEnd(DragEndDetails d) => setState(() => _dx = _dx < -_threshold ? -_max : 0.0);
  void _doDelete() { widget.onDelete(); setState(() => _dx = 0); }
  @override Widget build(BuildContext context) {
    final w = GestureDetector(
      onHorizontalDragUpdate: _onUpdate,
      onHorizontalDragEnd: _onEnd,
      child: Transform.translate(offset: Offset(_dx, 0), child: widget.child),
    );
    final red = Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      decoration: const BoxDecoration(color: Color(0xFFE53935), borderRadius: BorderRadius.all(Radius.circular(16))),
      child: const Align(alignment: Alignment.centerRight, child: Padding(padding: EdgeInsets.only(right: 20), child: Icon(Icons.delete_outline, color: Colors.white, size: 24))),
    );
    return GestureDetector(
      onTap: _dx < 0 ? _doDelete : widget.onTap,
      child: Stack(children: [Positioned.fill(child: red), w]),
    );
  }
}
