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

/// 反馈页（对应 Android FeedbackActivity）
class FeedbackPage extends ConsumerStatefulWidget {
  const FeedbackPage({super.key});

  @override
  ConsumerState<FeedbackPage> createState() => _FeedbackPageState();
}

class _FeedbackPageState extends ConsumerState<FeedbackPage> {
  final _content = TextEditingController();
  final _contact = TextEditingController();
  final List<String> _images = [];
  bool _submitting = false;

  @override
  void dispose() {
    _content.dispose();
    _contact.dispose();
    super.dispose();
  }

  Future<void> _pickImages() async {
    final files = await AlbumPicker.pick(max: 4);
    if (files.isEmpty) return;
    setState(() => _images.addAll(files));
  }

  Future<void> _submit() async {
    if (_content.text.trim().isEmpty) {
      Toast.error('请填写问题描述');
      return;
    }
    setState(() => _submitting = true);
    EasyLoading.show(status: '提交中…');
    try {
      List<String>? urls;
      if (_images.isNotEmpty) {
        urls = await ref
            .read(uploadServiceProvider)
            .uploadBatch(_images);
      }
      final r = await ref.read(userApiProvider).submitFeedback(
            content: _content.text.trim(),
            contact: _contact.text.trim().isEmpty
                ? null
                : _contact.text.trim(),
            images: urls,
          );
      EasyLoading.dismiss();
      if (!r.isSuccess) {
        Toast.error(r.message ?? '提交失败');
        return;
      }
      Toast.success('反馈已提交');
      if (mounted) Navigator.pop(context);
    } catch (e) {
      EasyLoading.dismiss();
      Toast.error('提交失败：$e');
    } finally {
      if (mounted) setState(() => _submitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('问题反馈')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
              controller: _content,
              maxLines: 6,
              decoration: const InputDecoration(
                hintText: '请描述您遇到的问题…',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _contact,
              decoration: const InputDecoration(
                labelText: '联系方式（选填）',
                hintText: '手机号/微信号',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            const Text('截图（选填）',
                style: TextStyle(color: Colors.grey)),
            const SizedBox(height: 8),
            PhotoThumbStrip(
              paths: _images,
              onAdd: _pickImages,
              onRemove: (i) => setState(() => _images.removeAt(i)),
            ),
            const SizedBox(height: 24),
            SizedBox(
              height: 48,
              child: ElevatedButton(
                onPressed: _submitting ? null : _submit,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).primaryColor,
                ),
                child: Text(_submitting ? '提交中…' : '提交反馈'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
