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

final _docProfileProvider = FutureProvider<Map<String, dynamic>?>((ref) async {
  final api = ref.read(apiClientProvider);
  final res = await api.get('/api/doctor/profile');
  return res.data['data'] as Map<String, dynamic>?;
});

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

class _DoctorProfileEditPageState extends ConsumerState<DoctorProfileEditPage> {
  final _name = TextEditingController();
  final _title = TextEditingController();
  final _dept = TextEditingController();
  final _hosp = TextEditingController();
  bool _saving = false;

  @override
  void dispose() {
    _name.dispose();
    _title.dispose();
    _dept.dispose();
    _hosp.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final prof = ref.watch(_docProfileProvider);
    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        surfaceTintColor: Colors.transparent,
        title: const Text(
          '个人信息',
          style: TextStyle(color: AppColors.textPrimary),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () => popRoute(ref),
        ),
      ),
      body: prof.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (_, _) => const Center(child: Text('加载失败')),
        data: (d) {
          if (d != null) {
            _name.text = d['name'] ?? '';
            _title.text = d['title'] ?? '';
            _dept.text = d['department'] ?? '';
            _hosp.text = d['hospital'] ?? '';
          }
          return ListView(
            padding: const EdgeInsets.all(16),
            children: [
              _Field('姓名', _name),
              const SizedBox(height: 12),
              _Field('职称', _title),
              const SizedBox(height: 12),
              _Field('科室', _dept),
              const SizedBox(height: 12),
              _Field('医院', _hosp),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _saving ? null : _save,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(14),
                    ),
                  ),
                  child: _saving
                      ? const CircularProgressIndicator(color: Colors.white)
                      : const Text('保存', style: TextStyle(fontSize: 16)),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Future<void> _save() async {
    setState(() => _saving = true);
    try {
      await ref
          .read(apiClientProvider)
          .put(
            '/api/doctor/profile',
            data: {
              'name': _name.text,
              'title': _title.text,
              'department': _dept.text,
              'hospital': _hosp.text,
            },
          );
      ref.invalidate(_docProfileProvider);
      if (mounted) {
        AppToast.show(context, '保存成功', type: AppToastType.success);
      }
    } catch (_) {
      if (mounted) {
        AppToast.show(context, '保存失败', type: AppToastType.error);
      }
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }
}

class _Field extends StatelessWidget {
  final String label;
  final TextEditingController ctrl;
  const _Field(this.label, this.ctrl);
  @override
  Widget build(BuildContext context) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 16),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(14),
      border: Border.all(color: AppColors.border),
    ),
    child: TextField(
      controller: ctrl,
      decoration: InputDecoration(
        labelText: label,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(14),
          borderSide: const BorderSide(color: Colors.transparent),
        ),
      ),
    ),
  );
}
