import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tasktracker/Categories.dart';
import 'package:tasktracker/Welcome.dart';
import 'package:tasktracker/splash.dart';
import 'package:wakelock/wakelock.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'NewTask.dart';
import 'newActivity.dart';
import 'Tasks.dart';
import 'User.dart' as User;


extension HexColor on Color {
  /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${alpha.toRadixString(16).padLeft(2, '0')}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';
}

// To keep the screen on:
final List<PopulationData> data = [
  PopulationData(
      name: "Rocket League",
      value: 45,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue)),
  PopulationData(
      name: "CS:GO",
      value: 15,
      barColor: charts.ColorUtil.fromDartColor(Colors.yellow)),
  PopulationData(
      name: "Halo",
      value: 10,
      barColor: charts.ColorUtil.fromDartColor(Colors.grey)),
  PopulationData(
      name: "SneakyPeaky",
      value: 30,
      barColor: charts.ColorUtil.fromDartColor(Colors.red)),
];

void main() {
  Wakelock.enable(); // or Wakelock.toggle(on: true);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          accentColor: Colors.redAccent,
          brightness: Brightness.dark,
          primaryColor: Colors.amber,
          fontFamily: 'Noto-Sans'),
      //home: const MyHomePage(),
      initialRoute: '/splash',
      routes:{
        '/splash':(context)=> const SplashScreen(),
        '/welcome':(context)=> const WelcomePage(),
        '/':(context) => const MyHomePage(),
        '/Tasks':(context)=> const Tasks(),
        '/Categories':(context)=>const Categories()
      }
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<charts.Series<PopulationData, String>> series = [
    charts.Series(
        id: "Subscribers",
        data: data,
        domainFn: (PopulationData series, _) => series.name,
        measureFn: (PopulationData series, _) => series.value,
        colorFn: (PopulationData series, _) => series.barColor)
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    showOfflineSnack();
  }

  void showOfflineSnack() async{
    await Future.delayed(const Duration(seconds: 1));
    if(User.offline){
      const SnackBar offlineSnack = SnackBar(content: Text('Offline'),duration: Duration(seconds: 100),);
      ScaffoldMessenger.of(context).showSnackBar(offlineSnack);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton.extended(onPressed: (){
          Navigator.of(context).push(MaterialPageRoute(builder: (context)=> NewActivity()));
        },
          label: Text("New Activity"),
          icon: Icon(Icons.add)
        ),
        appBar: AppBar(title: Row(children:[Icon(Icons.article_outlined, color: Theme.of(context).primaryColor),SizedBox(width: 10),Text('Summary')])),
        drawer: navDrawer(context,0),
        body: SafeArea(
          child: Container(
            child: Column(
              children: [
                Container(
                    height: 300,
                    padding: EdgeInsets.all(20),
                    child: Card(
                        elevation: 8,
                        shadowColor: Colors.blueGrey,
                        child: Padding(
                            padding: EdgeInsets.all(8),
                            child: Column(
                              children: [
                                cardTitle('Daily Average'),
                                Expanded(
                                    child: charts.BarChart(
                                  series,
                                  animate: true,
                                  barRendererDecorator:
                                      new charts.BarLabelDecorator(
                                          labelPosition:
                                              charts.BarLabelPosition.inside,
                                          labelPadding: 10,
                                          labelAnchor:
                                              charts.BarLabelAnchor.middle),
                                ))
                              ],
                            )))),
                Container(
                    height: 300,
                    padding: EdgeInsets.all(20),
                    child: Card(
                        elevation: 8,
                        shadowColor: Colors.green,
                        child: Padding(
                            padding: EdgeInsets.all(8),
                            child: Column(
                              children: [
                                cardTitle('Weekly Average'),
                                Expanded(
                                    child: charts.BarChart(
                                  series,
                                  animate: true,
                                  barRendererDecorator:
                                      new charts.BarLabelDecorator(
                                          labelPosition:
                                              charts.BarLabelPosition.inside,
                                          labelPadding: 10,
                                          labelAnchor:
                                              charts.BarLabelAnchor.middle),
                                ))
                              ],
                            ))))
              ],
            ),
          ),
        ));
  }
}

Widget cardTitle(String title) {
  return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children:[
        Padding(padding: EdgeInsets.all(20),child:Text(title,
            style: TextStyle(fontWeight: FontWeight.bold))),
        MaterialButton(onPressed: (){},child:moreButton())]);
}

Widget moreButton(){
  return MaterialButton(
    onPressed: (){

    },
    color: Colors.green,
      child:Row(
    children: [
      Text('More'),Icon(Icons.keyboard_arrow_right)
    ],
  ));
}

class PopulationData {
  String name;
  int value;
  charts.Color barColor;
  PopulationData(
      {required this.name, required this.value, required this.barColor});
}

Drawer navDrawer(BuildContext context, int pageIndex){
  return Drawer(
      child: ListView(
        children: [
          Padding(
              padding: EdgeInsets.all(16),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children:[Text("Time Tracker",
                      style: TextStyle(
                          fontSize: 25,
                          color: Theme.of(context).accentColor,
                          fontWeight: FontWeight.bold)),
                    Icon(Icons.more_time,size: 30,),
                  ])
          ),
          Divider(),
          ListTile(
            selected: (pageIndex == 0),
            title: Text('Summary'),
            leading: Icon(Icons.article_outlined,color: Theme.of(context).primaryColor),
            onTap: () {
              if(pageIndex==0){return;}
              Navigator.of(context).pushReplacementNamed('/');
            },
          ),
          ListTile(
            selected: (pageIndex == 1),
            title: Text('Analytics'),
            leading: Icon(Icons.analytics_outlined,color: Theme.of(context).primaryColor),
            onTap: () {
              if(pageIndex==1){return;}
              // Navigator.of(context).pushReplacementNamed('/');
            },
          ),
          Divider(),
          ListTile(
            selected: (pageIndex == 2),
            title: Text('Activities'),
            leading: Icon(Icons.task,color: Theme.of(context).primaryColor),
            onTap: () {
              if(pageIndex==2){return;}
              Navigator.of(context).pushReplacementNamed('/Activities');
            },
          ),
          ListTile(
            selected: (pageIndex == 3),
            title: Text('Task Types'),
            leading: Icon(Icons.task,color: Theme.of(context).primaryColor),
            onTap: () {
              if(pageIndex==3){return;}
              Navigator.of(context).pushReplacementNamed('/Tasks');
            },
          ),
          ListTile(
            selected: (pageIndex == 4),
            title: Text('Categories'),
            leading: Icon(Icons.account_tree_outlined,color: Theme.of(context).primaryColor),
            onTap: () {
              if(pageIndex==4){return;}
              Navigator.of(context).pushReplacementNamed('/Categories');
            },
          ),
          Divider(),
          ListTile(
            selected: (pageIndex == 5),
            title: Text('Settings'),
            leading: Icon(Icons.settings,color: Colors.blueGrey),
            onTap: () {
              
            },
          ),
          ListTile(
            selected: (pageIndex == 6),
            title: Text('About'),
            leading: Icon(Icons.help_outline_outlined),
            onTap: () {
              
            },
          ),
        ],
      ));
}