import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:initial_folder/providers/section_lesson_course_provider.dart';
import 'package:initial_folder/screens/course/component/expansion_tile_copy.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:provider/provider.dart';

class Aktifitas extends StatefulWidget {
  const Aktifitas({
    Key? key,
    required this.id,
    required this.totalDuration,
    this.resoaktifitas,
  }) : super(key: key);

  final String id;
  final String totalDuration;
  final String? resoaktifitas;

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

class _AktifitasState extends State<Aktifitas> {
  final _tileKeys = [];
  var _selectedIndex = -1;
  final List<ValueNotifier<bool>> _isExpanded = [];
  final ValueNotifier<int?> _selectedIndexNotifier = ValueNotifier<int?>(null);

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 10; i++) {
      _isExpanded.add(ValueNotifier<bool>(false));
    }
  }

  String formatDuration(String duration) {
    var parts = duration.split(':');
    String formattedDuration = '';

    if (parts[0] != '00') {
      formattedDuration += '${parts[0]} jam ';
    }
    formattedDuration +=
        '${int.parse(parts[1])} menit ${int.parse(parts[2])} detik';

    return '($formattedDuration)';
  }

  String formatDurations(String duration) {
    if (duration == '') {
      String formattedDuration = '';

      print('masuk sini');
      formattedDuration += '';
      return formattedDuration;
    }
    List<String> parts = duration.split(':');
    int hours = int.parse(parts[0]);
    int minutes = int.parse(parts[1]);

    String formattedDuration = '';

    if (hours != 0) {
      formattedDuration += '${hours}j';
    }

    if (minutes != 0) {
      formattedDuration += '${int.parse(parts[1])}m';
    }

    formattedDuration += '${int.parse(parts[2])}d';

    return formattedDuration;
  }

  void resetExpansionTileKeysAndSelectedIndex() {
    _tileKeys.clear();
    _selectedIndex = -1;
  }

  @override
  Widget build(BuildContext context) {
    String _parseHtmlString(String htmlText) {
      RegExp exp = RegExp(r"<[^>]*>|&nbsp;|&amp;|&quot;",
          multiLine: true, caseSensitive: true);
      return htmlText.replaceAll(exp, '');
    }

    resetExpansionTileKeysAndSelectedIndex();
    return Container(
      margin: EdgeInsets.only(
        left: getProportionateScreenWidth(15),
        right: getProportionateScreenWidth(15),
        top: getProportionateScreenHeight(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Aktivitas',
            style: thirdTextStyle.copyWith(
              fontWeight: semiBold,
              fontSize: getProportionateScreenWidth(14),
            ),
          ),
          SizedBox(
            height: 8,
          ),
          Consumer<SectionLessonCourseProvider>(
            builder: (context, state, _) {
              if (state.state == ResultState.Loading) {
                return Center(
                  child: CircularProgressIndicator(
                    color: Colors.amber,
                    strokeWidth: 2,
                  ),
                );
              } else if (state.state == ResultState.HasData) {
                _isExpanded.clear();
                for (int i = 0; i < state.result!.data![0].length; i++) {
                  _isExpanded.add(ValueNotifier<bool>(false));
                }
                return Container(
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Text(
                            '${state.result!.data![0].length} Pelajaran',
                            style: thirdTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(11),
                              fontWeight: light,
                            ),
                          ),
                          SizedBox(width: getProportionateScreenWidth(6)),
                          Text(
                            formatDuration(widget.totalDuration == ""
                                ? "00:02:07"
                                : widget.totalDuration),
                            style: thirdTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(11),
                              fontWeight: light,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: getProportionateScreenHeight(5)),
                      Container(
                        height: widget.resoaktifitas == null
                            ? getProportionateScreenHeight(195)
                            : getProportionateScreenHeight(195),
                        width: SizeConfig.screenWidth,
                        child: ListView.builder(
                          itemCount: state.result!.data![0].length,
                          itemBuilder: (context, index) {
                            var chapter = state.result!.data![0][index];
                            final tileKey = GlobalKey();
                            _tileKeys.add(tileKey);
                            return ValueListenableBuilder<bool>(
                              valueListenable: _isExpanded[index],
                              builder: (context, isExpanded, child) {
                                return Theme(
                                    data: ThemeData.dark().copyWith(
                                      colorScheme: ColorScheme.dark(
                                          primary: secondaryColor),
                                      dividerColor: Colors.transparent,
                                    ),
                                    child: Padding(
                                      padding: EdgeInsets.only(
                                          bottom:
                                              getProportionateScreenHeight(15)),
                                      child: Column(
                                        children: [
                                          ListTileTheme(
                                            dense: true,
                                            child: Container(
                                              decoration: BoxDecoration(
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .primaryContainer,
                                                borderRadius:
                                                    BorderRadius.circular(5),
                                                boxShadow: [
                                                  BoxShadow(
                                                    color: baruTexthitam
                                                        .withOpacity(0.1),
                                                    blurRadius: 3,
                                                    spreadRadius: 1,
                                                    offset: Offset(0, 3),
                                                  ),
                                                ],
                                              ),
                                              child: ExpansionTileCopy(
                                                key: tileKey,
                                                onExpansionChanged:
                                                    (bool expanding) {
                                                  if (expanding) {
                                                    if (_selectedIndexNotifier
                                                                .value !=
                                                            null &&
                                                        _selectedIndexNotifier
                                                                .value !=
                                                            index &&
                                                        _tileKeys[_selectedIndexNotifier
                                                                    .value!]
                                                                .currentState !=
                                                            null) {
                                                      _tileKeys[
                                                              _selectedIndexNotifier
                                                                  .value!]
                                                          .currentState!
                                                          .closeExpansion();
                                                    }
                                                    _selectedIndexNotifier
                                                        .value = index;
                                                  } else if (_selectedIndexNotifier
                                                          .value ==
                                                      index) {
                                                    _selectedIndexNotifier
                                                        .value = null;
                                                  }
                                                },
                                                title: Text(
                                                  'Bab ${index + 1}',
                                                  style:
                                                      thirdTextStyle.copyWith(
                                                    fontWeight: semiBold,
                                                    fontSize:
                                                        getProportionateScreenWidth(
                                                            11),
                                                    color: Theme.of(context)
                                                        .colorScheme
                                                        .onBackground,
                                                  ),
                                                ),
                                                subtitle: Html(
                                                  shrinkWrap: true,
                                                  data: chapter.title ?? '',
                                                  style: {
                                                    "body": Style(
                                                      margin: Margins.zero,
                                                      padding:
                                                          HtmlPaddings.zero,
                                                      fontSize: FontSize(
                                                          getProportionateScreenWidth(
                                                              12)),
                                                      fontWeight: reguler,
                                                      fontFamily: 'Poppins',
                                                      color: Theme.of(context)
                                                          .colorScheme
                                                          .onBackground,
                                                    ),
                                                  },
                                                ),
                                                trailing:
                                                    ValueListenableBuilder<
                                                        int?>(
                                                  valueListenable:
                                                      _selectedIndexNotifier,
                                                  builder:
                                                      (context, value, child) {
                                                    return Icon(
                                                      value == index
                                                          ? Icons.remove
                                                          : Icons.add,
                                                      color: primaryColor,
                                                    );
                                                  },
                                                ),
                                                children: chapter.dataLesson![0]
                                                    .asMap()
                                                    .entries
                                                    .map(
                                                      (e) => ListTile(
                                                        minVerticalPadding: 15,
                                                        leading: Text(
                                                          '${e.key + 1}',
                                                          style: thirdTextStyle
                                                              .copyWith(
                                                            color: Theme.of(
                                                                    context)
                                                                .colorScheme
                                                                .onBackground,
                                                          ),
                                                        ),
                                                        minLeadingWidth: 15,
                                                        title:
                                                            Transform.translate(
                                                          offset: Offset(0, 0),
                                                          child: Text(
                                                            _parseHtmlString(e
                                                                    .value
                                                                    .titleLesson ??
                                                                ''),
                                                            style: TextStyle(
                                                              fontSize:
                                                                  getProportionateScreenWidth(
                                                                      12),
                                                              fontWeight:
                                                                  semiBold,
                                                              fontFamily:
                                                                  'Poppins',
                                                              color: Theme.of(
                                                                      context)
                                                                  .colorScheme
                                                                  .onBackground,
                                                            ),
                                                          ),
                                                        ),
                                                        subtitle:
                                                            Transform.translate(
                                                          offset: Offset(0, 0),
                                                          child: Text(
                                                            (e.value.lessonType ==
                                                                    'video')
                                                                ? 'Video - ${formatDuration(e.value.duration.toString())}'
                                                                : (e.value.lessonType ==
                                                                        'quiz')
                                                                    ? 'Quiz'
                                                                    : (e.value
                                                                            .attachment
                                                                            .toString()
                                                                            .contains('.pdf'))
                                                                        ? 'PDFs'
                                                                        : (e.value.attachment.toString().contains('.pptx'))
                                                                            ? 'PPT'
                                                                            : (e.value.attachment.toString().contains('.rar'))
                                                                                ? 'RAR'
                                                                                : (e.value.attachment.toString().contains('.zip'))
                                                                                    ? 'ZIP'
                                                                                    : (e.value.attachment.toString().contains('.xlsx'))
                                                                                        ? 'Excel'
                                                                                        : (e.value.attachment.toString().contains('.jpg') || e.value.attachment.toString().contains('.jpeg') || e.value.attachment.toString().contains('.png'))
                                                                                            ? 'Image'
                                                                                            : (e.value.attachment.toString().contains('.docx'))
                                                                                                ? 'Document'
                                                                                                : (e.value.attachment.toString().contains('.txt'))
                                                                                                    ? 'Text'
                                                                                                    : 'Terjadi Kesalahan',
                                                            style:
                                                                thirdTextStyle
                                                                    .copyWith(
                                                              color: Theme.of(
                                                                      context)
                                                                  .colorScheme
                                                                  .onBackground,
                                                              fontSize:
                                                                  getProportionateScreenHeight(
                                                                      8),
                                                            ),
                                                          ),
                                                        ),
                                                        trailing: (e.value
                                                                    .lessonType ==
                                                                'video')
                                                            ? Image.asset(
                                                                'assets/images/play_button_new.png',
                                                                color: Theme.of(
                                                                        context)
                                                                    .colorScheme
                                                                    .onBackground,
                                                                scale: 3,
                                                              )
                                                            : (e.value.lessonType ==
                                                                    'quiz')
                                                                ? Image.asset(
                                                                    'assets/icons/lms/ListNumbers.png',
                                                                    color: Theme.of(
                                                                            context)
                                                                        .colorScheme
                                                                        .onBackground,
                                                                    scale:
                                                                        getProportionateScreenWidth(
                                                                            1.3),
                                                                  )
                                                                : (e.value
                                                                        .attachment
                                                                        .toString()
                                                                        .contains(
                                                                            '.pdf'))
                                                                    ? Image
                                                                        .asset(
                                                                        'assets/icons/lms/FilePdf.png',
                                                                        color: Theme.of(context)
                                                                            .colorScheme
                                                                            .onBackground,
                                                                        scale: getProportionateScreenWidth(
                                                                            1.3),
                                                                      )
                                                                    : (e.value
                                                                            .attachment
                                                                            .toString()
                                                                            .contains(
                                                                                '.rar'))
                                                                        ? Image
                                                                            .asset(
                                                                            'assets/icons/lms/FileArchive.png',
                                                                            color:
                                                                                Theme.of(context).colorScheme.onBackground,
                                                                            scale:
                                                                                getProportionateScreenWidth(1.3),
                                                                          )
                                                                        : (e.value.attachment.toString().contains('.zip'))
                                                                            ? Image.asset(
                                                                                'assets/icons/lms/FileZip.png',
                                                                                color: Theme.of(context).colorScheme.onBackground,
                                                                                scale: getProportionateScreenWidth(1.3),
                                                                              )
                                                                            : (e.value.attachment.toString().contains('.pptx'))
                                                                                ? Image.asset(
                                                                                    'assets/icons/lms/FilePpt.png',
                                                                                    color: Theme.of(context).colorScheme.onBackground,
                                                                                    scale: getProportionateScreenWidth(1.3),
                                                                                  )
                                                                                : (e.value.attachment.toString().contains('.xlsx'))
                                                                                    ? Image.asset(
                                                                                        'assets/icons/lms/FileXls.png',
                                                                                        color: Theme.of(context).colorScheme.onBackground,
                                                                                        scale: getProportionateScreenWidth(1.3),
                                                                                      )
                                                                                    : (e.value.attachment.toString().contains('.jpg') || e.value.attachment.toString().contains('.jpeg') || e.value.attachment.toString().contains('.png'))
                                                                                        ? Image.asset(
                                                                                            'assets/icons/lms/FileImage.png',
                                                                                            color: Theme.of(context).colorScheme.onBackground,
                                                                                            scale: getProportionateScreenWidth(1.3),
                                                                                          )
                                                                                        : (e.value.attachment.toString().contains('.txt'))
                                                                                            ? Image.asset(
                                                                                                'assets/icons/lms/FileText.png',
                                                                                                color: Theme.of(context).colorScheme.onBackground,
                                                                                                scale: getProportionateScreenWidth(1.3),
                                                                                              )
                                                                                            : ((e.value.attachment.toString().contains('.docx')))
                                                                                                ? Image.asset(
                                                                                                    'assets/icons/lms/FileDoc.png',
                                                                                                    color: Theme.of(context).colorScheme.onBackground,
                                                                                                    scale: getProportionateScreenWidth(1.3),
                                                                                                  )
                                                                                                : SizedBox(),
                                                      ),
                                                    )
                                                    .toList(),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ));
                              },
                            );
                          },
                        ),
                      )
                    ],
                  ),
                );
              } else if (state.state == ResultState.NoData) {
                return Center(child: Text(state.message));
              } else if (state.state == ResultState.Error) {
                return Center(
                  child: Padding(
                    padding:
                        EdgeInsets.only(top: getProportionateScreenHeight(30)),
                    child: Text(
                      'Kursus ini belum memiliki aktivitas',
                      style: thirdTextStyle.copyWith(),
                    ),
                  ),
                );
              } else {
                return Center(child: Text(''));
              }
            },
          ),
        ],
      ),
    );
  }
}
