import 'package:finnow_app/api/profile.dart';
import 'package:finnow_app/auth/model.dart';
import 'package:finnow_app/main.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

/// A list item that shows a profile in the user's list of all profiles.
class ProfileListItem extends StatelessWidget {
  final Profile profile;
  final Function onDeletedCallback;
  const ProfileListItem(this.profile, this.onDeletedCallback, {super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: const EdgeInsets.all(10),
        margin: const EdgeInsets.only(top: 10, bottom: 10),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: const Color.fromARGB(255, 236, 236, 236)),
        constraints: const BoxConstraints(maxWidth: 200),
        child: Row(children: [
          Expanded(child: Text(profile.name)),
          ElevatedButton(
            child: const Text('View'),
            onPressed: () => getIt<GoRouter>().go('/profiles/${profile.name}'),
          ),
          const SizedBox(width: 5),
          IconButton(
            icon: const Icon(Icons.delete),
            onPressed: () => attemptDeleteProfile(context),
          )
        ]));
  }

  void attemptDeleteProfile(BuildContext ctx) async {
    bool confirmed = false;
    await showDialog(
        context: ctx,
        builder: (context) {
          return AlertDialog(
              title: const Text('Confirm Profile Deletion'),
              content: const Text(
                  'Are you sure you want to delete this profile? This will permamently delete all accounts, transactions, and other data in this profile. This data is not recoverable.'),
              actions: [
                FilledButton(
                    onPressed: () {
                      confirmed = true;
                      Navigator.of(context).pop();
                    },
                    child: const Text('Ok')),
                FilledButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('Cancel'))
              ]);
        });
    if (confirmed) {
      final auth = getIt<AuthenticationModel>();
      if (auth.state is Authenticated) {
        await deleteProfile((auth.state as Authenticated).token, profile);
        onDeletedCallback();
      }
    }
  }
}
