import 'package:autosos_flutter/model/user.dart';
import 'package:autosos_flutter/provider/providers.dart';
import 'package:autosos_flutter/util/toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// 完善资料页（对应 Android MePerfectActivity）
class PerfectPage extends ConsumerStatefulWidget {
  const PerfectPage({super.key});

  @override
  ConsumerState<PerfectPage> createState() => _PerfectPageState();
}

class _PerfectPageState extends ConsumerState<PerfectPage> {
  final _formKey = GlobalKey<FormState>();
  final _realName = TextEditingController();
  final _idCard = TextEditingController();
  final _phone = TextEditingController();
  final _address = TextEditingController();
  final _email = TextEditingController();
  final _company = TextEditingController();
  bool _loading = false;
  UserInfo? _user;

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

  @override
  void dispose() {
    _realName.dispose();
    _idCard.dispose();
    _phone.dispose();
    _address.dispose();
    _email.dispose();
    _company.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    final resp = await ref.read(userApiProvider).info();
    if (!mounted || !resp.isSuccess) return;
    final u = resp.data!;
    setState(() {
      _user = u;
      _realName.text = u.realName ?? '';
      _idCard.text = u.idCard ?? '';
      _phone.text = u.phone ?? '';
      _address.text = u.address ?? '';
      _email.text = u.email ?? '';
      _company.text = u.company ?? '';
    });
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _loading = true);
    EasyLoading.show(status: '保存中…');
    try {
      final resp = await ref.read(userApiProvider).perfectInfo({
        'real_name': _realName.text.trim(),
        'id_card': _idCard.text.trim(),
        'phone': _phone.text.trim(),
        'address': _address.text.trim(),
        'email': _email.text.trim(),
        'company': _company.text.trim(),
      });
      EasyLoading.dismiss();
      if (!resp.isSuccess) {
        Toast.error(resp.message ?? '保存失败');
        return;
      }
      ref.read(currentUserProvider.notifier).state = resp.data;
      Toast.success('保存成功');
      if (mounted) Navigator.pop(context);
    } catch (e) {
      EasyLoading.dismiss();
      Toast.error('保存失败：$e');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('完善资料')),
      body: _user == null
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _realName,
                      decoration: const InputDecoration(
                        labelText: '真实姓名',
                        border: OutlineInputBorder(),
                      ),
                      validator: (v) =>
                          (v == null || v.isEmpty) ? '请输入姓名' : null,
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: _idCard,
                      decoration: const InputDecoration(
                        labelText: '身份证号',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: _phone,
                      keyboardType: TextInputType.phone,
                      decoration: const InputDecoration(
                        labelText: '联系电话',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: _email,
                      keyboardType: TextInputType.emailAddress,
                      decoration: const InputDecoration(
                        labelText: '邮箱',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: _company,
                      decoration: const InputDecoration(
                        labelText: '所属公司（选填）',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: _address,
                      maxLines: 2,
                      decoration: const InputDecoration(
                        labelText: '常住地址',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 24),
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: _loading ? null : _submit,
                        style: ElevatedButton.styleFrom(
                          backgroundColor:
                              Theme.of(context).primaryColor,
                          minimumSize: const Size.fromHeight(48),
                        ),
                        child: Text(_loading ? '保存中…' : '保存'),
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}
