import 'dart:html';

import 'package:flutter/material.dart';
import 'package:grpc/grpc_web.dart';
import 'package:softplayer_web/api/grpc/accounts.dart';
import 'package:softplayer_web/components/environments.dart';
import 'package:softplayer_web/components/login_form.dart';

void main() async {
  const String backendURL = String.fromEnvironment(
    'SOFTPLAYER_BACKEND_URL',
    defaultValue: 'https://softplayer-backend.badhouseplants.net:8080',
  );
  GrpcWebClientChannel grpcChannel =
      GrpcWebClientChannel.xhr(Uri.parse(backendURL));

  runApp(MyApp(channel: grpcChannel));
}

class MyApp extends StatelessWidget {
  MyApp({super.key, required this.channel});
  final GrpcWebClientChannel channel;
  late final AccountsGrpc accountsGrpc = AccountsGrpc(channel: channel);
  @override
  Widget build(BuildContext context) {
    accountsGrpc.init();
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Softplayer',
      home: Scaffold(
        body: TestAlert(channel: channel),
        appBar: AppBar(),
        floatingActionButton: FloatingActionButton(
          onPressed: () => print("1"),
        ),
      ),
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
    );
  }
}

class TestAlert extends StatelessWidget {
  final GrpcWebClientChannel channel;
  TestAlert({super.key, required this.channel});
  late final AccountsGrpc accountsGrpc = AccountsGrpc(channel: channel);
  bool isSignedIn() {
    return window.localStorage.containsKey("token");
  }

  @override
  Widget build(BuildContext context) {
    if (!isSignedIn()) {
      return Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/login_background.jpg"),
            fit: BoxFit.fill,
          ),
        ),
        child: LoginForm(grpcChannel: channel),
      );
    } else {
      return EnvirnomentList(channel: channel);
    }
  }
}
