import 'package:absenkuv3/UI/Template/DatePicker/Bloc/DatePickerMulaiBloc.dart';
import 'package:absenkuv3/UI/Template/templateForm.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';

// ignore: must_be_immutable
class TemplateDatePickerMulai extends StatefulWidget {
  String title;
  DateTime? initialData;
  double height;
  TemplateDatePickerMulai(this.title, {this.initialData, this.height = 46});

  @override
  _TemplateDatePickerMulaiState createState() => _TemplateDatePickerMulaiState();
}

class _TemplateDatePickerMulaiState extends State<TemplateDatePickerMulai> {
  DateTime selectedDate = DateTime.now();
  final dateFormat = new DateFormat('dd-MM-yyyy');

  @override
  void initState() {
    super.initState();
    if(widget.initialData!=null) BlocProvider.of<DatePickerMulaiBloc>(context).add(SetDate(widget.initialData));
    else BlocProvider.of<DatePickerMulaiBloc>(context).add(SetDate(DateTime.now()));
    /*if(widget.initialData!=null){
      DateTime todayDate = DateTime.parse(widget);
    }*/
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DatePickerMulaiBloc, DateTime>(
      builder: (BuildContext context, DateTime date){
        // ignore: unnecessary_null_comparison
        if(date!=null) return GestureDetector(
          onTap: () async{
            final DateTime? picked = await showDatePicker(
                context: context,
                initialDate: date,
                firstDate: DateTime(2015, 8),
                lastDate: DateTime(2101));
            if (picked != null && picked != selectedDate) BlocProvider.of<DatePickerMulaiBloc>(context).add(SetDate(picked));
          },
          child: Container(
            child: TemplateForm(
              enabled: false,
              prefixIcon: Icon(Icons.calendar_today, size: 20,),titleText:"${widget.title}:",hintText:dateFormat.format(date), radius: 6, formHeight: widget.height, color: Colors.grey[600],),
          ),
        );
        else return Container();
      },
    );
  }
}
