import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../controls/padding.dart';
import '../controls/standard_appbar.dart';
import '../services/connections_manager.dart';
import '../utils/active_profile_selector.dart';
import '../utils/snackbar_builder.dart';

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

  @override
  State<CircleCreateScreen> createState() => _CircleCreateScreenState();
}

class _CircleCreateScreenState extends State<CircleCreateScreen> {
  final circleTextController = TextEditingController();

  Future<void> createCircle(ConnectionsManager manager) async {
    if (circleTextController.text.isEmpty) {
      buildSnackbar(context, "Circle name can't be empty");
      return;
    }

    final result = await manager.createCircle(circleTextController.text);
    if (context.mounted) {
      result.match(
          onSuccess: (_) => context.canPop() ? context.pop() : null,
          onError: (error) {
            buildSnackbar(context, 'Error trying to create new circle: $error');
          });
    }
  }

  @override
  Widget build(BuildContext context) {
    final manager = context
        .watch<ActiveProfileSelector<ConnectionsManager>>()
        .activeEntry
        .value;

    return Scaffold(
      appBar: StandardAppBar.build(
        context,
        'New circle',
        withHome: false,
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            TextFormField(
              controller: circleTextController,
              textCapitalization: TextCapitalization.sentences,
              decoration: InputDecoration(
                labelText: 'Circle Name',
                border: OutlineInputBorder(
                  borderSide: const BorderSide(),
                  borderRadius: BorderRadius.circular(5.0),
                ),
              ),
            ),
            const VerticalPadding(),
            ElevatedButton(
              onPressed: () => createCircle(manager),
              child: const Text('Create'),
            ),
          ],
        ),
      ),
    );
  }
}
