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';
import '../../utils/backoffice_formatters.dart';
import '../../widgets/backoffice_ui.dart';

final _reportsProvider = FutureProvider<List<Map<String, dynamic>>>((
  ref,
) async {
  final api = ref.read(apiClientProvider);
  final res = await api.get('/api/doctor/reports');
  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);
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              _FilterChip(
                '全部',
                '',
                _filter,
                () => setState(() => _filter = ''),
              ),
              _FilterChip(
                '待审核',
                'PendingDoctor',
                _filter,
                () => setState(() => _filter = 'PendingDoctor'),
              ),
              _FilterChip(
                '已审核',
                'DoctorReviewed',
                _filter,
                () => setState(() => _filter = 'DoctorReviewed'),
              ),
            ],
          ),
        ),
        Expanded(
          child: reports.when(
            loading: () => const BackofficeLoadingState(message: '正在加载报告'),
            error: (_, _) => BackofficeErrorState(
              onRetry: () => ref.invalidate(_reportsProvider),
            ),
            data: (allItems) {
              final items = _filter.isEmpty
                  ? allItems
                  : allItems
                        .where((item) => item['status'] == _filter)
                        .toList();
              return items.isEmpty
                  ? const BackofficeEmptyState(
                      icon: Icons.description_outlined,
                      title: '暂无报告',
                      description: '患者上传的待审核报告会显示在这里',
                    )
                  : ListView.builder(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      itemCount: items.length,
                      itemBuilder: (_, i) {
                        final r = items[i];
                        return BackofficeSectionCard(
                          margin: const EdgeInsets.only(bottom: 8),
                          padding: const EdgeInsets.all(14),
                          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'] ?? '未分类'} · '
                              '${formatBackofficeDateTime(r['createdAt'])}',
                            ),
                            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,
          ),
        ),
      ),
    );
  }
}
