import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:typed_data';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_js/flutter_js.dart';
import 'package:csv/csv.dart';
import 'package:collection/collection.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'SheetJS x Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
        useMaterial3: true,
      ),
      home: const SheetJSFlutter(),
    );
  }
}

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

  @override
  State<SheetJSFlutter> createState() => SheetJSFlutterState();
}

class SheetJSFlutterState extends State<SheetJSFlutter> {
  String _version = '0.0.0';
  List<List<dynamic>> _data = [];
  late JavascriptRuntime _engine;

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

  void _async() async {
    await _initEngine();
    await _fetch();
  }

  Future<void> _initEngine() async {
    /* load scripts */
    _engine = getJavascriptRuntime();
    String shim = await rootBundle.loadString("scripts/shim.min.js");
    _engine.evaluate(shim);
    String sheetjs = await rootBundle.loadString("scripts/xlsx.full.min.js");
    _engine.evaluate(sheetjs);
    JsEvalResult vers = _engine.evaluate("XLSX.version");
    setState(() => _version = vers.stringResult);
  }

  Future<void> _fetch() async {
    final res = await http.get(Uri.parse("https://sheetjs.com/pres.numbers"));
    if (res.statusCode == 200)
      _processBytes(res.bodyBytes);
    else
      throw Exception("Failed to fetch file");
  }

  void _processBytes(Uint8List bytes) {
    String base64 = base64Encode(bytes);
    JsEvalResult func = _engine.evaluate("""
      var wb = XLSX.read('$base64');
      XLSX.utils.sheet_to_csv(wb.Sheets[wb.SheetNames[0]]);
    """);
    setState(() {
      _data = CsvToListConverter(eol: "\n").convert(func.stringResult);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text('SheetJS x Flutter $_version'),
      ),
      body: Table(
        children: _data.mapIndexed((R, row) => TableRow(
          decoration: BoxDecoration(color: R == 0 ? Colors.blue[50] : null),
          children: row.mapIndexed((C, cell) => Text(cell.toString())).toList()
        )).toList()
      ),
    );
  }
}

