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

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

class MyHomePage extends StatefulWidget {
  final Config config;

  const MyHomePage({super.key, required this.config});

  @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.readSecure(SecureStorageKey.url);
    final jwt = await _storageHelper.readSecure(SecureStorageKey.jwt);
    apiClient = ApiClient(baseUrl: "${url!}/api", token: jwt);
    // TODO: check if really logged in
    final sheets = await apiClient!.fetchSheets();
    log.info("${sheets.length} sheets fetched");
    final sheetsSorted = await sortSheetsByAccessTime(sheets);
    log.info("${sheetsSorted.length} sheets sorted");
    return sheetsSorted;
  }

  Future<List<Sheet>> sortSheetsByAccessTime(List<Sheet> sheets) async {
    final accessTimes = await _storageHelper.readSheetAccessTimes();

    sheets.sort((a, b) {
      final dateA = accessTimes[a.uuid];
      final dateB = accessTimes[b.uuid];

      if (dateB == null) {
        // b has no date, sort below a
        return -1;
      } else if (dateA == null) {
        // a has no date, sort below b
        return 1;
      } else {
        // compare both and sort by date
        return dateB.compareTo(dateA);
      }
    });

    return sheets;
  }

  Future<void> _logOut() async {
    // Delete saved jwt
    await _storageHelper.writeSecure(SecureStorageKey.jwt, null);

    if (!mounted) return; // Widget already removed

    Navigator.of(
      context,
    ).pushReplacement(MaterialPageRoute(builder: (_) => LoginPage()));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Sheetless"),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            tooltip: 'Logout',
            onPressed: _logOut,
          ),
        ],
      ),
      body: FutureBuilder(
        future: acquireSheets(),
        builder: (BuildContext context, AsyncSnapshot<List<Sheet>> snapshot) {
          if (snapshot.hasData) {
            return SheetsWidget(
              sheets: snapshot.data!,
              onSheetOpenRequest: (sheet) {
                _storageHelper.writeSheetAccessTime(sheet.uuid, DateTime.now());
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => SheetViewerPage(
                      sheet: sheet,
                      apiClient: apiClient!,
                      config: widget.config,
                    ),
                  ),
                );
              },
            );
          } 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());
          }
        },
      ),
    );
  }
}
