import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';
import '../../widgets/app_toast.dart';

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

class DoctorFollowUpEditPage extends ConsumerStatefulWidget {
  final String? id;
  const DoctorFollowUpEditPage({super.key, this.id});
  @override
  ConsumerState<DoctorFollowUpEditPage> createState() =>
      _DoctorFollowUpEditPageState();
}

class _DoctorFollowUpEditPageState
    extends ConsumerState<DoctorFollowUpEditPage> {
  final _titleCtrl = TextEditingController();
  final _notesCtrl = TextEditingController();
  String? _pid;
  DateTime _date = DateTime.now().add(const Duration(days: 7));
  TimeOfDay _time = const TimeOfDay(hour: 9, minute: 0);
  bool _saving = false;
  bool _loaded = false;

  bool get isEdit => widget.id != null && widget.id!.isNotEmpty;

  @override
  void dispose() {
    _titleCtrl.dispose();
    _notesCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (isEdit && !_loaded) {
      ref.watch(_fupDetailForEdit(widget.id!)).whenData((d) {
        if (d != null) {
          _loaded = true;
          _titleCtrl.text = d['title'] ?? '';
          _notesCtrl.text = d['notes'] ?? '';
          _pid = d['userId']?.toString();
          final at = DateTime.tryParse(d['scheduledAt']?.toString() ?? '');
          if (at != null) {
            _date = at;
            _time = TimeOfDay.fromDateTime(at);
          }
        }
      });
    }

    final pts = ref.watch(_ptsSimple);

    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        surfaceTintColor: Colors.transparent,
        title: Text(
          isEdit ? '编辑随访' : '新建随访',
          style: const TextStyle(color: AppColors.textPrimary),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () => popRoute(ref),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          const Text(
            '患者',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          pts.when(
            loading: () => const LinearProgressIndicator(),
            error: (_, _) => const Text('加载失败'),
            data: (list) => _dropdown(list),
          ),
          const SizedBox(height: 16),
          _input('随访标题', _titleCtrl, hint: '例：术后一个月复查'),
          const SizedBox(height: 16),
          const Text(
            '随访时间',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          _dateTimePicker(),
          const SizedBox(height: 16),
          _input('备注', _notesCtrl, hint: '随访备注（可选）', maxLines: 4),
          const SizedBox(height: 28),
          _submitBtn(),
        ],
      ),
    );
  }

  Widget _dropdown(List<Map<String, dynamic>> list) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 16),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(14),
      border: Border.all(color: AppColors.border),
    ),
    child: DropdownButtonHideUnderline(
      child: DropdownButton<String?>(
        isExpanded: true,
        value: _pid,
        hint: const Text('选择患者', style: TextStyle(color: AppColors.textHint)),
        items: [
          const DropdownMenuItem<String?>(
            value: null,
            child: Text('选择患者', style: TextStyle(color: AppColors.textHint)),
          ),
          ...list.map(
            (p) => DropdownMenuItem<String?>(
              value: p['id']?.toString(),
              child: Text(
                '${p['name'] ?? p['phone']} (${p['phone']})',
                style: const TextStyle(fontSize: 15),
              ),
            ),
          ),
        ],
        onChanged: (v) => setState(() {
          _pid = v;
        }),
      ),
    ),
  );

  Widget _input(
    String label,
    TextEditingController ctrl, {
    String? hint,
    int maxLines = 1,
  }) => Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(
        label,
        style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
      ),
      const SizedBox(height: 8),
      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,
          maxLines: maxLines,
          decoration: InputDecoration(
            hintText: hint,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: const BorderSide(color: Colors.transparent),
            ),
          ),
        ),
      ),
    ],
  );

  Widget _dateTimePicker() => Row(
    children: [
      Expanded(
        child: GestureDetector(
          onTap: () async {
            final d = await showAppDatePicker(
              context,
              initialDate: _date,
              firstDate: DateTime.now(),
              lastDate: DateTime.now().add(const Duration(days: 365)),
            );
            if (d != null) setState(() => _date = d);
          },
          child: _pickerBox(_displayDate(_date)),
        ),
      ),
      const SizedBox(width: 12),
      Expanded(
        child: GestureDetector(
          onTap: () async {
            final t = await showAppTimePicker(context, initialTime: _time);
            if (t != null) setState(() => _time = t);
          },
          child: _pickerBox(
            '${_time.hour.toString().padLeft(2, '0')}:${_time.minute.toString().padLeft(2, '0')}',
          ),
        ),
      ),
    ],
  );

  Widget _pickerBox(String text) => Container(
    padding: const EdgeInsets.symmetric(vertical: 14),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(14),
      border: Border.all(color: AppColors.border),
    ),
    child: Center(child: Text(text, style: const TextStyle(fontSize: 15))),
  );

  Widget _submitBtn() => 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)
          : Text(
              isEdit ? '保存修改' : '创建随访',
              style: const TextStyle(fontSize: 16),
            ),
    ),
  );

  Future<void> _save() async {
    if (_pid == null) {
      _snack('请选择患者');
      return;
    }
    if (_titleCtrl.text.trim().isEmpty) {
      _snack('请输入随访标题');
      return;
    }
    setState(() => _saving = true);
    final at = DateTime(
      _date.year,
      _date.month,
      _date.day,
      _time.hour,
      _time.minute,
    );
    try {
      final api = ref.read(apiClientProvider);
      final data = {
        'userId': _pid,
        'title': _titleCtrl.text.trim(),
        'scheduledAt': at.toIso8601String(),
        'notes': _notesCtrl.text.trim().isEmpty ? null : _notesCtrl.text.trim(),
      };
      if (isEdit) {
        await api.put('/api/doctor/follow-ups/${widget.id}', data: data);
      } else {
        await api.post('/api/doctor/follow-ups', data: data);
      }
      if (mounted) {
        _snack(isEdit ? '修改成功' : '创建成功', ok: true);
        popRoute(ref);
      }
    } catch (e) {
      if (mounted) _snack('保存失败: $e');
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  void _snack(String msg, {bool ok = false}) {
    AppToast.show(
      context,
      msg,
      type: ok ? AppToastType.success : AppToastType.error,
    );
  }
}

final _fupDetailForEdit = FutureProvider.family<Map<String, dynamic>?, String>((
  ref,
  id,
) async {
  final api = ref.read(apiClientProvider);
  final res = await api.get('/api/doctor/follow-ups');
  final items = (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
  return items.cast<Map<String, dynamic>?>().firstWhere(
    (f) => f?['id']?.toString() == id,
    orElse: () => null,
  );
});

String _displayDate(DateTime date) {
  return '${date.year}/${date.month.toString().padLeft(2, '0')}/${date.day.toString().padLeft(2, '0')}';
}
