import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:intl/intl.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:tasktracker/NewJournal.dart';
import 'package:tasktracker/main.dart';
import 'User.dart' as User;
import 'Dialogs.dart';

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

  @override
  State<JournalPage> createState() => _JournalPageState();
}

class _JournalPageState extends State<JournalPage>{

  bool selecting = false;
  List<int> selectedIndexes = [];
  int expandedIndex = -1;
  var refreshStream;

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

    refreshStream = User.refreshStream.stream.listen((event) {if(!event){setState(() {

    });}});

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    refreshStream?.close();
  }
  bool searching =false;
  TextEditingController searchController = TextEditingController();
  FocusNode _focus = FocusNode();
  @override
  Widget build(BuildContext context) {
    bool landscape=((MediaQuery.of(context).size.width / MediaQuery.of(context).size.height) > 1);
    return Scaffold(
      floatingActionButton: FloatingActionButton.extended(
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewJournal())).then((val) {
              setState(() {});
            });
          },
          label: Text("New Entry"),
          icon: Icon(Icons.add)),
      appBar: AppBar(
        title: (searching)
            ? Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Expanded(
                  child: TextField(
                    onChanged: (text) {
                      setState(() {});
                    },
                    controller: searchController,
                    focusNode: _focus,
                    decoration: InputDecoration(
                      filled: true,
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    searching = false;
                    searchController.clear();
                    setState(() {});
                  },
                  child: Container(
                    margin: EdgeInsets.all(10),
                    child: Icon(Icons.cancel),
                  ),
                )
              ],
            )
          ],
        ) :
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                FaIcon(FontAwesomeIcons.bookJournalWhills),
                SizedBox(
                  width: 15,
                ),
                Text('Journal')
              ],
            ),
            Row(
              children: [
                if(selecting && selectedIndexes.length > 0)InkWell(onTap:() async{
                  selecting=false;
                  for (int element in selectedIndexes) {
                    await User.UserOperations.deleteJournal(User.journal[element].id);
                  }setState(() {

                  });
                },child: Container(margin:EdgeInsets.all(8),child: Icon(Icons.delete))),
                if(selecting)InkWell(onTap:(){
                  selecting=false;
                  setState(() {

                  });
                },child: Container(margin:EdgeInsets.all(8),child: Icon(Icons.cancel))),
                InkWell(onTap:(){
                  searching=true;
                  searchController.clear();
                  setState(() {

                  });
                },child: Container(margin:EdgeInsets.all(8),child: Icon(Icons.search))),
                if(!selecting)InkWell(onTap:(){setState(() {

                });},child: Container(margin: EdgeInsets.all(8), child: Icon(Icons.refresh),))
              ],
            )
          ],
        ),
      ),
      drawer: landscape ? null : navDrawer(context, 8),
      body: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          landscape?navDrawer(context, 8) : Container(),
          Expanded(
            child: Container(
              padding: EdgeInsets.all(8),
              child: ScrollablePositionedList.builder(
                  itemCount: User.journal.length,
                  itemBuilder: (context, index) {
                    int charCount = '\n'.allMatches(User.journal[index].description ?? '').length * 50;
                    charCount +=(User.journal[index].description ?? '').length;
                    int maxCharCount = 100;

                    bool matchesSearch = false;
                    if(searching && searchController.text.isNotEmpty){
                      if(User.journal[index].title != null && User.journal[index].title!.toLowerCase().contains(searchController.text.toLowerCase())){
                        matchesSearch = true;
                      }
                      if((User.journal[index].description ?? '').toLowerCase().contains(searchController.text.toLowerCase())){
                        matchesSearch=true;
                      }
                    }else{
                      matchesSearch =true;
                    }

                    return (matchesSearch) ? Container(
                        child: InkWell(
                          onTap: (){
                            if(selecting){
                              if(selectedIndexes.contains(index)){
                                selectedIndexes.remove(index);
                              }else{
                                selectedIndexes.add(index);
                              }
                              setState(() {

                              });
                            }else{
                              if(expandedIndex==index){
                                expandedIndex=-1;
                                //_controller..reverse(from: 0.5);
                              }else {
                                expandedIndex = index;
                               // _controller..forward(from: 0);
                              }
                              setState(() {

                              });
                            }
                          },
                      onLongPress: () {
                        selecting = !selecting;
                        if(!selectedIndexes.contains(index)){selectedIndexes.add(index);}
                        setState(() {});
                      },
                      child: Row(
                        children: [
                          if (selecting)
                            Checkbox(
                              value: selectedIndexes.contains(index),
                              onChanged: (newVal) {
                                if(selectedIndexes.contains(index)){
                                  selectedIndexes.remove(index);
                                }else{
                                  selectedIndexes.add(index);
                                }
                                setState(() {

                                });
                              },
                            ),
                          Expanded(
                            child: Card(
                                child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: AnimatedContainer(
                                duration: Duration(seconds: 1),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        (User.journal[index].title!=null && User.journal[index].title!.isNotEmpty) ?
                                        Text(User.journal[index].title!, style: TextStyle(fontSize: 18)) :
                                        Text(DateFormat('MMMM-dd').format( User.journal[index].day),  style: TextStyle(fontSize: 18)),
                                        Container(padding:EdgeInsets.symmetric(horizontal: 10,vertical: 2),decoration: BoxDecoration(borderRadius: BorderRadius.circular(20),color: Colors.black26),child: Text(DateFormat('yyyy-MM-dd').format(User.journal[index].day)))
                                      ],
                                    ),
                                    SizedBox(height: 5,),
                                    if (User.journal[index].description != null && User.journal[index].description!.isNotEmpty)
                                      (charCount > maxCharCount && expandedIndex != index) ?
                                      Text(User.journal[index].description!.substring(0,maxCharCount.clamp(0,User.journal[index].description!.length)) + '...')  :
                                      Text(User.journal[index].description!),

                                    if(charCount>maxCharCount) Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Container(),
                                        (index == expandedIndex)? Icon(Icons.keyboard_arrow_up) : Icon(Icons.keyboard_arrow_down)

                                      ],
                                    )
                                  ],
                                ),
                              ),
                            ),
                            ),
                          ),
                          if(selecting)InkWell(onTap:(){
                            Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewJournal(date: User.journal[index].day, title: User.journal[index].title, text: User.journal[index].description,))).then((val) {
                              setState(() {});
                            });
                            selecting=false;
                            setState(() {

                            });
                          },child: Container(margin:EdgeInsets.all(8),child: FaIcon(FontAwesomeIcons.edit)))
                        ],
                      ),
                    )) : Container();
                  }),
            ),
          ),
        ],
      ),
    );
  }
}
