import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:telemednet/data_service.dart';
import 'package:telemednet/primary_button.dart';
import 'package:telemednet/route_names.dart';

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

  @override
  State<LaunchScreen> createState() => _LaunchScreenState();
}

class _LaunchScreenState extends State<LaunchScreen> {
  late Timer _timer;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/cover-picture.jpg'),
                fit: BoxFit.cover,
              ),
            ),
            child: Container(
              alignment: Alignment.bottomCenter,
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      color: const Color.fromARGB(200, 255, 255, 255),
                    ),
                    child: SizedBox(
                      height: 150,
                      width: double.infinity,
                      child: Padding(
                        padding: const EdgeInsets.all(18.0),
                        child: Center(
                            child: Column(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              'TeleMedNet',
                              style: Theme.of(context).textTheme.titleLarge,
                            ),
                            StreamBuilder(
                                stream:
                                    FirebaseAuth.instance.authStateChanges(),
                                builder: (context, snapshot) {
                                  if (snapshot.connectionState ==
                                      ConnectionState.waiting) {
                                    return const CircularProgressIndicator();
                                  } else if (snapshot.hasData) {
                                    _timer =
                                        Timer(const Duration(seconds: 3), () {
                                      try {
                                        DataService.getProfile()
                                            .then((profile) {
                                          if (profile == null) {
                                            // ignore: use_build_context_synchronously
                                            Navigator.of(context)
                                                .pushReplacementNamed(
                                                    RouteNames.userProfile);
                                          } else {
                                            // ignore: use_build_context_synchronously
                                            Navigator.of(context)
                                                .pushReplacementNamed(
                                                    RouteNames.userHome);
                                          }
                                        });
                                      } finally {}
                                      _timer.cancel();
                                    });
                                    return _buildProceedingWidget(context);
                                  } else {
                                    return _buildSignInSignUpRow(context);
                                  }
                                })
                          ],
                        )),
                      ),
                    )),
              ),
            )));
  }

  Widget _buildProceedingWidget(BuildContext context) {
    return const Column(
      children: [
        CircularProgressIndicator(),
        SizedBox(height: 10),
        Text('Please wait...')
      ],
    );
  }

  Widget _buildSignInSignUpRow(BuildContext context) {
    return Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
              child: ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).pushNamed(RouteNames.signUp);
                  },
                  child: const Text('Sign Up'))),
          const SizedBox(width: 10),
          Expanded(
              child: PrimaryButton(
            onPressed: () {
              Navigator.of(context).pushNamed(RouteNames.signIn);
            },
            text: 'Sign In',
          )),
        ]);
  }
}
