import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../core/navigation_provider.dart';
import '../../providers/data_providers.dart'
    show adminServiceProvider, doctorListProvider;
import '../../providers/backoffice_refresh_providers.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/backoffice_ui.dart';

class AdminAddDoctorPage extends ConsumerStatefulWidget {
  final String? id;
  final String initialPhone;
  final String initialName;
  final String initialTitle;
  final String initialDepartment;
  final String initialDirection;

  const AdminAddDoctorPage({
    super.key,
    this.id,
    this.initialPhone = '',
    this.initialName = '',
    this.initialTitle = '',
    this.initialDepartment = '',
    this.initialDirection = '',
  });
  @override
  ConsumerState<AdminAddDoctorPage> createState() => _AdminAddDoctorPageState();
}

class _AdminAddDoctorPageState extends ConsumerState<AdminAddDoctorPage> {
  late final TextEditingController _phoneCtrl;
  late final TextEditingController _nameCtrl;
  late final TextEditingController _titleCtrl;
  late final TextEditingController _deptCtrl;
  late final TextEditingController _directionCtrl;
  bool _saving = false;

  bool get _isEdit => widget.id?.isNotEmpty == true;

  @override
  void initState() {
    super.initState();
    _phoneCtrl = TextEditingController(text: widget.initialPhone);
    _nameCtrl = TextEditingController(text: widget.initialName);
    _titleCtrl = TextEditingController(text: widget.initialTitle);
    _deptCtrl = TextEditingController(text: widget.initialDepartment);
    _directionCtrl = TextEditingController(text: widget.initialDirection);
  }

  @override
  void dispose() {
    _phoneCtrl.dispose();
    _nameCtrl.dispose();
    _titleCtrl.dispose();
    _deptCtrl.dispose();
    _directionCtrl.dispose();
    super.dispose();
  }

  Future<void> _save() async {
    if (_phoneCtrl.text.trim().isEmpty) {
      AppToast.show(context, '手机号不能为空', type: AppToastType.warning);
      return;
    }
    if (_nameCtrl.text.trim().isEmpty) {
      AppToast.show(context, '姓名不能为空', type: AppToastType.warning);
      return;
    }
    setState(() => _saving = true);
    try {
      final data = {
        'phone': _phoneCtrl.text.trim(),
        'name': _nameCtrl.text.trim(),
        'title': _titleCtrl.text.trim(),
        'department': _deptCtrl.text.trim(),
        'professionalDirection': _directionCtrl.text.trim(),
      };
      if (_isEdit) {
        await ref.read(adminServiceProvider).updateDoctor(widget.id!, data);
      } else {
        await ref.read(adminServiceProvider).addDoctor(data);
      }
      if (mounted) {
        ref.invalidate(doctorListProvider);
        ref.read(adminDoctorsRefreshSignalProvider.notifier).trigger();
        AppToast.show(
          context,
          _isEdit ? '修改成功' : '添加成功',
          type: AppToastType.success,
        );
        popRoute(ref);
      }
    } catch (e) {
      if (mounted) {
        AppToast.show(
          context,
          '${_isEdit ? '修改' : '添加'}失败: $e',
          type: AppToastType.error,
        );
      }
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        surfaceTintColor: Colors.transparent,
        title: Text(
          _isEdit ? '编辑医生' : '新增医生',
          style: const TextStyle(color: AppColors.textPrimary),
        ),
        iconTheme: const IconThemeData(color: AppColors.textPrimary),
      ),
      body: BackofficeSurface(
        child: SingleChildScrollView(
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _buildField('手机号 *', _phoneCtrl, TextInputType.phone),
              const SizedBox(height: 16),
              _buildField('姓名 *', _nameCtrl, TextInputType.name),
              const SizedBox(height: 16),
              _buildField('职称', _titleCtrl, TextInputType.text),
              const SizedBox(height: 16),
              _buildField('科室', _deptCtrl, TextInputType.text),
              const SizedBox(height: 16),
              _buildField('专业方向', _directionCtrl, TextInputType.text),
              const SizedBox(height: 32),
              SizedBox(
                height: 50,
                child: ElevatedButton(
                  onPressed: _saving ? null : _save,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: _saving
                      ? const CircularProgressIndicator(color: Colors.white)
                      : Text(
                          _isEdit ? '保存修改' : '保存',
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.white,
                          ),
                        ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildField(
    String label,
    TextEditingController ctrl,
    TextInputType type,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: AppColors.textPrimary,
          ),
        ),
        const SizedBox(height: 8),
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
          ),
          child: TextField(
            controller: ctrl,
            keyboardType: type,
            decoration: InputDecoration(
              filled: true,
              fillColor: Colors.white,
              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),
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 13,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
