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';

final _fupRefresh = FutureProvider<String?>((ref) async {
  final api = ref.read(apiClientProvider);
  final res = await api.get('/api/doctor/follow-ups');
  final items = (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
  ref.read(_fupList.notifier).replace(items);
  return null;
});

final _fupList = NotifierProvider<FupListN, List<Map<String, dynamic>>>(
  FupListN.new,
);

class FupListN extends Notifier<List<Map<String, dynamic>>> {
  @override
  List<Map<String, dynamic>> build() => [];
  void replace(List<Map<String, dynamic>> v) => state = v;
  void markDone(String id) => state = state
      .map((f) => f['id'] == id ? {...f, 'status': 'Completed'} : f)
      .toList();
  void remove(String id) => state = state.where((f) => f['id'] != id).toList();
}

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

class _DoctorFollowupsPageState extends ConsumerState<DoctorFollowupsPage> {
  String _filter = '';

  @override
  void initState() {
    super.initState();
    Future.microtask(() => ref.read(_fupRefresh));
  }

  @override
  Widget build(BuildContext context) {
    var items = ref.watch(_fupList);
    if (_filter == 'Upcoming') {
      items = items.where((f) => f['status'] == 'Upcoming').toList();
    } else if (_filter == 'Completed') {
      items = items.where((f) => f['status'] == 'Completed').toList();
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              _Filt('全部', _filter == '', () => setState(() => _filter = '')),
              const SizedBox(width: 8),
              _Filt(
                '待完成',
                _filter == 'Upcoming',
                () => setState(() => _filter = 'Upcoming'),
              ),
              const SizedBox(width: 8),
              _Filt(
                '已完成',
                _filter == 'Completed',
                () => setState(() => _filter = 'Completed'),
              ),
              const Spacer(),
              IconButton(
                icon: const Icon(Icons.add, color: AppColors.primary),
                onPressed: () => pushRoute(ref, 'doctorFollowUpEdit'),
              ),
            ],
          ),
        ),
        Expanded(
          child: RefreshIndicator(
            onRefresh: () => ref.refresh(_fupRefresh.future),
            child: items.isEmpty
                ? ListView(
                    children: const [
                      SizedBox(height: 100),
                      Center(
                        child: Text(
                          '暂无随访',
                          style: TextStyle(color: AppColors.textHint),
                        ),
                      ),
                    ],
                  )
                : ListView.builder(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    itemCount: items.length,
                    itemBuilder: (_, i) {
                      final f = items[i];
                      final upcoming = f['status'] == 'Upcoming';
                      return Container(
                        margin: const EdgeInsets.only(bottom: 8),
                        padding: const EdgeInsets.all(14),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(14),
                          border: Border.all(color: AppColors.border),
                          boxShadow: AppColors.cardShadowLight,
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Expanded(
                                  child: Text(
                                    f['title'] ?? '',
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w600,
                                      fontSize: 15,
                                    ),
                                  ),
                                ),
                                Container(
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 8,
                                    vertical: 3,
                                  ),
                                  decoration: BoxDecoration(
                                    color:
                                        (upcoming
                                                ? AppColors.warning
                                                : AppColors.success)
                                            .withValues(alpha: 0.1),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Text(
                                    upcoming ? '待完成' : '已完成',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: upcoming
                                          ? AppColors.warning
                                          : AppColors.success,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '${f['patientName'] ?? ''} · ${(f['scheduledAt'] ?? '').toString().substring(0, 16)}',
                              style: const TextStyle(
                                fontSize: 13,
                                color: AppColors.textHint,
                              ),
                            ),
                            if (f['notes'] != null)
                              Padding(
                                padding: const EdgeInsets.only(top: 4),
                                child: Text(
                                  f['notes']!,
                                  style: const TextStyle(
                                    fontSize: 13,
                                    color: AppColors.textSecondary,
                                  ),
                                ),
                              ),
                            if (upcoming) ...[
                              const SizedBox(height: 8),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  TextButton(
                                    onPressed: () => pushRoute(
                                      ref,
                                      'doctorFollowUpEdit',
                                      params: {'id': f['id']?.toString() ?? ''},
                                    ),
                                    child: const Text(
                                      '编辑',
                                      style: TextStyle(fontSize: 13),
                                    ),
                                  ),
                                  TextButton(
                                    onPressed: () async {
                                      await ref
                                          .read(apiClientProvider)
                                          .put(
                                            '/api/doctor/follow-ups/${f['id']}',
                                            data: {'status': 'Completed'},
                                          );
                                      ref
                                          .read(_fupList.notifier)
                                          .markDone(f['id']?.toString() ?? '');
                                    },
                                    child: const Text(
                                      '完成',
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: Color(0xFF10B981),
                                      ),
                                    ),
                                  ),
                                  TextButton(
                                    onPressed: () async {
                                      await ref
                                          .read(apiClientProvider)
                                          .delete(
                                            '/api/doctor/follow-ups/${f['id']}',
                                          );
                                      ref
                                          .read(_fupList.notifier)
                                          .remove(f['id']?.toString() ?? '');
                                    },
                                    child: const Text(
                                      '删除',
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: AppColors.error,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ],
                        ),
                      );
                    },
                  ),
          ),
        ),
      ],
    );
  }
}

class _Filt extends StatelessWidget {
  final String label;
  final bool active;
  final VoidCallback onTap;
  const _Filt(this.label, this.active, this.onTap);
  @override
  Widget build(BuildContext context) => GestureDetector(
    onTap: onTap,
    child: Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7),
      decoration: BoxDecoration(
        color: active ? AppColors.primary : Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: active ? AppColors.primary : AppColors.border,
        ),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 13,
          color: active ? Colors.white : AppColors.textSecondary,
        ),
      ),
    ),
  );
}
