import 'package:finnow_app/auth/model.dart';
import 'package:finnow_app/components/profile_list_item.dart';
import 'package:flutter/material.dart';

import '../api/profile.dart';
import '../main.dart';

class ProfilesPage extends StatelessWidget {
  const ProfilesPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: const Padding(
          padding: EdgeInsets.all(10),
          child: Column(children: [
            Text('Select a Profile',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 32.0)),
            SizedBox(height: 10),
            Expanded(child: _ProfilesListView()),
          ])),
      floatingActionButton: FloatingActionButton(
          onPressed: () => print('pressed'), child: const Icon(Icons.add)),
    );
  }
}

class _ProfilesListView extends StatefulWidget {
  const _ProfilesListView();

  @override
  State<_ProfilesListView> createState() => __ProfilesListViewState();
}

class __ProfilesListViewState extends State<_ProfilesListView> {
  List<Profile> profiles = List.empty();

  @override
  Widget build(BuildContext context) {
    return ListView(
      scrollDirection: Axis.vertical,
      children: profiles.map((p) => ProfileListItem(p, () => refreshProfiles())).toList(),
    );
  }

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

  void refreshProfiles() async {
    setState(() => profiles = List.empty());
    final authState = getIt<AuthenticationModel>().state;
    if (authState is Authenticated) {
      final List<Profile> latestProfiles = await getProfiles(authState.token);
      setState(() => profiles = latestProfiles);
    }
  }
}
