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

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

class _DoctorPatientsPageState extends ConsumerState<DoctorPatientsPage> {
  final _searchCtrl = TextEditingController();
  List<Map<String, dynamic>> _patients = [];
  int _page = 1;
  bool _loading = false;
  bool _hasMore = true;
  int _total = 0;
  String? _error;

  @override
  void initState() {
    super.initState();
    _load();
  }

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

  Future<void> _load({bool reset = false}) async {
    if (_loading) return;
    if (reset) {
      _page = 1;
      _patients.clear();
      _error = null;
    }
    setState(() => _loading = true);
    try {
      final api = ref.read(apiClientProvider);
      final params = <String, dynamic>{'page': _page, 'pageSize': 20};
      final search = _searchCtrl.text.trim();
      if (search.isNotEmpty) params['search'] = search;
      final res = await api.get(
        '/api/doctor/patients',
        queryParameters: params,
      );
      final data = res.data['data'];
      if (!mounted) return;
      if (data != null) {
        final items =
            (data['items'] as List?)?.cast<Map<String, dynamic>>() ?? [];
        setState(() {
          if (reset) {
            _patients = items;
          } else {
            _patients.addAll(items);
          }
          _total = data['total'] ?? 0;
          _hasMore = _patients.length < _total;
          _page++;
        });
      }
    } catch (_) {
      if (mounted) setState(() => _error = '患者列表加载失败');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _onSearch() async {
    await _load(reset: true);
  }

  Future<void> _loadMore() async {
    if (_hasMore) await _load();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: TextField(
            controller: _searchCtrl,
            onSubmitted: (_) => _onSearch(),
            decoration: InputDecoration(
              hintText: '搜索患者姓名或手机号',
              prefixIcon: const Icon(Icons.search, color: AppColors.textHint),
              suffixIcon: _searchCtrl.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        _searchCtrl.clear();
                        _onSearch();
                      },
                    )
                  : null,
              filled: true,
              fillColor: Colors.white,
              contentPadding: const EdgeInsets.symmetric(vertical: 12),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: const BorderSide(color: AppColors.border),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: const BorderSide(color: AppColors.border),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: const BorderSide(color: AppColors.primary),
              ),
            ),
          ),
        ),
        Expanded(
          child: _patients.isEmpty && _loading
              ? const BackofficeLoadingState(message: '正在加载患者')
              : _patients.isEmpty && _error != null
              ? BackofficeErrorState(
                  message: _error!,
                  onRetry: () => _load(reset: true),
                )
              : RefreshIndicator(
                  onRefresh: () => _load(reset: true),
                  child: _patients.isEmpty && !_loading
                      ? ListView(
                          children: const [
                            SizedBox(
                              height: 360,
                              child: BackofficeEmptyState(
                                icon: Icons.people_outline,
                                title: '暂无患者数据',
                                description: '与您关联的患者会显示在这里',
                              ),
                            ),
                          ],
                        )
                      : ListView.builder(
                          padding: const EdgeInsets.symmetric(horizontal: 16),
                          itemCount: _patients.length + (_hasMore ? 1 : 0),
                          itemBuilder: (_, i) {
                            if (i >= _patients.length) {
                              return Padding(
                                padding: const EdgeInsets.all(16),
                                child: Center(
                                  child: _loading
                                      ? const CircularProgressIndicator(
                                          strokeWidth: 2,
                                        )
                                      : TextButton.icon(
                                          onPressed: _loadMore,
                                          icon: const Icon(Icons.expand_more),
                                          label: const Text('加载更多'),
                                        ),
                                ),
                              );
                            }
                            final p = _patients[i];
                            return _PatientTile(
                              p: p,
                              onTap: () => pushRoute(
                                ref,
                                'doctorPatientDetail',
                                params: {'id': p['id']?.toString() ?? ''},
                              ),
                            );
                          },
                        ),
                ),
        ),
      ],
    );
  }
}

class _PatientTile extends StatelessWidget {
  final Map<String, dynamic> p;
  final VoidCallback onTap;
  const _PatientTile({required this.p, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final gender = p['gender'] ?? '';
    final genderIcon = gender == 'Male'
        ? Icons.male
        : gender == 'Female'
        ? Icons.female
        : Icons.person;
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.only(bottom: 8),
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: AppColors.border),
          boxShadow: AppColors.cardShadowLight,
        ),
        child: Row(
          children: [
            CircleAvatar(
              radius: 22,
              backgroundColor: AppColors.avatarBg,
              child: Icon(genderIcon, color: AppColors.primary),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    p['name'] ?? p['phone'] ?? '',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  Text(
                    p['phone'] ?? '',
                    style: const TextStyle(
                      fontSize: 13,
                      color: AppColors.textHint,
                    ),
                  ),
                ],
              ),
            ),
            const Icon(Icons.chevron_right, color: AppColors.textHint),
          ],
        ),
      ),
    );
  }
}
