import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:sheetless/sheet_viewer_page.dart';
import 'package:sheetless/storage_helper.dart';

import 'api.dart';
import 'sheet.dart';

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ApiClient? apiClient;
  Future<bool> apiLoggedIn = Future.value(false);
  final StorageHelper _storageHelper = StorageHelper();
  final log = Logger("MyHomePage");

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

  Future<List<Sheet>> acquireSheets() async {
    final url = await _storageHelper.read(StorageKey.url);
    final jwt = await _storageHelper.read(StorageKey.jwt);
    apiClient = ApiClient(baseUrl: url!, token: jwt);
    // TODO: check if really logged in
    final sheets = await apiClient!.fetchSheets();
    log.info("${sheets.length} sheets fetched");
    return sheets;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("My Sheets"),
      ),
      body: FutureBuilder(
          future: acquireSheets(),
          builder: (BuildContext context, AsyncSnapshot<List<Sheet>> snapshot) {
            if (snapshot.hasData) {
              return SheetsWidget(
                sheets: snapshot.data!,
                callback: (sheet) => Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => SheetViewerPage(
                      sheet: sheet,
                      apiClient: apiClient!,
                    ),
                  ),
                ),
              );
            } else if (snapshot.hasError) {
              return Center(
                  child: Text(
                      style: Theme.of(context)
                          .textTheme
                          .displaySmall!
                          .copyWith(color: Colors.red),
                      textAlign: TextAlign.center,
                      snapshot.error.toString()));
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          }),
    );
  }
}
