import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:qpay/screens/groups/models/recipient_group_model.dart';
import 'package:qpay/models/responsive_policy.dart';
import 'package:qpay/screens/groups/controllers/group_controller.dart';
import 'package:qpay/widgets/app_snack_bar.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../recipient/recipients_controller.dart';

class GroupCreateScreen extends StatefulWidget {
  const GroupCreateScreen({super.key});

  @override
  State<GroupCreateScreen> createState() => _GroupCreateScreenState();
}

class _GroupCreateScreenState extends State<GroupCreateScreen> {
  late GroupController controller;
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _recipientsController = TextEditingController();

  @override
  void initState() {
    super.initState();
    controller = GroupController(context);
  }

  @override
  void dispose() {
    controller.dispose();
    _nameController.dispose();
    _descriptionController.dispose();
    _recipientsController.dispose();
    super.dispose();
  }

  List<Recipient> _parseRecipients(String raw) {
    final lines = raw
        .split('\n')
        .map((l) => l.trim())
        .where((l) => l.isNotEmpty)
        .toList();
    final List<Recipient> members = [];
    for (final line in lines) {
      final parts = line.split(',');
      if (parts.length >= 2) {
        final name = parts[0].trim();
        final account = parts[1].trim();
        String phone = '';
        if (parts.length > 2) {
          phone = parts.sublist(2).join(',').trim();
        }
        if (name.isNotEmpty && account.isNotEmpty) {
          members.add(
            Recipient(
              name: name,
              account: account,
              phoneNumber: phone,
              latestProviderLabel: '',
            ),
          );
        }
      }
    }
    return members;
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;

    final recipients = _parseRecipients(_recipientsController.text);
    if (recipients.isEmpty) {
      AppSnackBar.show(
        context,
        'Please add at least one recipient in name,account format.',
      );
      return;
    }

    final prefs = await SharedPreferences.getInstance();
    final userId = prefs.getString('userId') ?? '';
    final workspaceId = prefs.getString('workspaceId') ?? '';

    final req = CreateGroupRequest(
      name: _nameController.text.trim(),
      description: _descriptionController.text.trim().isEmpty
          ? null
          : _descriptionController.text.trim(),
      userId: userId,
      workspaceId: workspaceId,
      recipients: recipients,
    );

    final result = await controller.createGroup(req);
    if (!mounted) return;

    if (result.isSuccess) {
      AppSnackBar.showSuccess(context, 'Group created successfully.');
      context.pop(true); // Return true to indicate a new group was created
    } else {
      AppSnackBar.showError(context, result.error ?? 'Failed to create group.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('New Group'), centerTitle: true),
      body: ListenableBuilder(
        listenable: controller,
        builder: (context, _) {
          return Center(
            child: LayoutBuilder(
              builder: (context, constraints) {
                final width = constraints.maxWidth > ResponsivePolicy.md
                    ? ResponsivePolicy.md.toDouble()
                    : constraints.maxWidth;
                return SizedBox(
                  width: width,
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(20),
                    child: Form(
                      key: _formKey,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          TextFormField(
                            controller: _nameController,
                            textInputAction: TextInputAction.next,
                            decoration: InputDecoration(
                              labelText: 'Group Name',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                            validator: (v) => (v == null || v.trim().isEmpty)
                                ? 'Group name is required'
                                : null,
                          ),
                          const SizedBox(height: 16),
                          TextFormField(
                            controller: _descriptionController,
                            textInputAction: TextInputAction.next,
                            decoration: InputDecoration(
                              labelText: 'Description (optional)',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                          ),
                          const SizedBox(height: 24),
                          Text(
                            'Recipients',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey.shade800,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'Enter one recipient per line as: name,account',
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey.shade600,
                            ),
                          ),
                          const SizedBox(height: 8),
                          TextFormField(
                            controller: _recipientsController,
                            maxLines: 8,
                            keyboardType: TextInputType.multiline,
                            textInputAction: TextInputAction.newline,
                            decoration: InputDecoration(
                              hintText:
                                  'Alice,263773000001\nBob,263773000002\nCarol,263773000003',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              alignLabelWithHint: true,
                            ),
                          ),
                          const SizedBox(height: 32),
                          ElevatedButton(
                            onPressed: controller.model.isLoading
                                ? null
                                : _submit,
                            style: ElevatedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(vertical: 16),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                            child: controller.model.isLoading
                                ? const SizedBox(
                                    height: 20,
                                    width: 20,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      color: Colors.white,
                                    ),
                                  )
                                : const Text(
                                    'Create Group',
                                    style: TextStyle(fontSize: 16),
                                  ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}
