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 _reportsProvider =
    FutureProvider.family<List<Map<String, dynamic>>, String>((
      ref,
      status,
    ) async {
      final api = ref.read(apiClientProvider);
      final params = <String, dynamic>{};
      if (status.isNotEmpty && status != 'All') params['status'] = status;
      final res = await api.get(
        '/api/doctor/reports',
        queryParameters: params.isNotEmpty ? params : null,
      );
      return (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
    });

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

class _DoctorReportsPageState extends ConsumerState<DoctorReportsPage> {
  String _filter = '';

  @override
  Widget build(BuildContext context) {
    final reports = ref.watch(_reportsProvider(_filter));
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              _FilterChip(
                '全部',
                '',
                _filter,
                () => setState(() => _filter = ''),
              ),
              const SizedBox(width: 8),
              _FilterChip(
                '待审核',
                'PendingDoctor',
                _filter,
                () => setState(() => _filter = 'PendingDoctor'),
              ),
              const SizedBox(width: 8),
              _FilterChip(
                '已审核',
                'DoctorReviewed',
                _filter,
                () => setState(() => _filter = 'DoctorReviewed'),
              ),
            ],
          ),
        ),
        Expanded(
          child: reports.when(
            loading: () => const Center(child: CircularProgressIndicator()),
            error: (_, _) => const Center(child: Text('加载失败')),
            data: (items) => items.isEmpty
                ? const Center(
                    child: Text(
                      '暂无报告',
                      style: TextStyle(color: AppColors.textHint),
                    ),
                  )
                : ListView.builder(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    itemCount: items.length,
                    itemBuilder: (_, i) {
                      final r = items[i];
                      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: ListTile(
                          contentPadding: EdgeInsets.zero,
                          leading: Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: AppColors.iconBg,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Icon(
                              Icons.description_outlined,
                              color: AppColors.primary,
                            ),
                          ),
                          title: Text(
                            r['patientName'] ?? '',
                            style: const TextStyle(fontWeight: FontWeight.w600),
                          ),
                          subtitle: Text(
                            '${r['category'] ?? ''} · ${r['createdAt'] ?? ''}'
                                .replaceAll('T', ' ')
                                .substring(0, 16),
                          ),
                          trailing: const Icon(
                            Icons.chevron_right,
                            color: AppColors.textHint,
                          ),
                          onTap: () => pushRoute(
                            ref,
                            'doctorReportDetail',
                            params: {'id': r['id']?.toString() ?? ''},
                          ),
                        ),
                      );
                    },
                  ),
          ),
        ),
      ],
    );
  }
}

class _FilterChip extends StatelessWidget {
  final String label, value, current;
  final VoidCallback onTap;
  const _FilterChip(this.label, this.value, this.current, this.onTap);
  @override
  Widget build(BuildContext context) {
    final active = value == current;
    return 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,
          ),
          boxShadow: active
              ? AppColors.buttonShadow
              : AppColors.cardShadowLight,
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 13,
            color: active ? Colors.white : AppColors.textSecondary,
          ),
        ),
      ),
    );
  }
}
