import 'package:flutter/material.dart';
import 'package:voyagehandbook/util/drawer.dart';
import 'package:voyagehandbook/util/storage.dart';
import 'package:voyagehandbook/util/styles.dart';
import 'package:voyagehandbook/views/pageview.dart';

import 'package:flutter_gen/gen_l10n/app_localizations.dart';

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

  @override
  State<DownloadsView> createState() => _DownloadsViewState();
}

class _DownloadsViewState extends State<DownloadsView> {
  @override
  void initState() {
    super.initState();
    loadDownloads();
  }

  var _content = <Widget>[];
  var _isLoading = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context)!.downloadsTitle),
      ),
      drawer: genDrawer(3, context),
      body: Center(
        child: SizedBox(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width * 0.9,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: _isLoading
                ? [const CircularProgressIndicator()]
                : _content.isEmpty
                    ? [
                        Text(
                          AppLocalizations.of(context)!.noDownloads,
                          textAlign: TextAlign.center,
                        )
                      ]
                    : _content,
          ),
        ),
      ),
    );
  }

  void loadDownloads() async {
    var files = await StorageAccess.offline;
    _content = List.generate(
      files.length,
      (index) => SizedBox(
        width: MediaQuery.of(context).size.width * 0.9,
        height: MediaQuery.of(context).size.height * 0.1,
        child: InkWell(
          onTap: () => Navigator.of(context).push(
            MaterialPageRoute(
              builder: (_) => ArticleView(
                pageKey: files[index]["key"],
                name: files[index]["title"],
              ),
            ),
          ),
          child: Align(
            alignment: Alignment.center,
            child: Text(
              files[index]["title"],
              textAlign: TextAlign.center,
              style: PageStyles.h1,
            ),
          ),
        ),
      ),
    );
    _isLoading = false;
    setState(() {});
  }
}
