import 'dart:convert';

import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:initial_folder/models/detail_course_model.dart';
import 'package:initial_folder/providers/detail_course_provider.dart';
import 'package:initial_folder/providers/section_lesson_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/screens/detail_course/components/instruktur.dart';
import 'package:initial_folder/screens/detail_course/components/kursus_include_item.dart';
import 'package:provider/provider.dart';

import '../../../size_config.dart';
import '../../../theme.dart';

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

  @override
  State<DetailPlayCourse> createState() => _DetailPlayCourseState();
}

class _DetailPlayCourseState extends State<DetailPlayCourse> {
  bool isExpanded = false;
  bool isExpanded2 = false;

  @override
  Widget build(BuildContext context) {
    final Brightness brightnessValue =
        MediaQuery.of(context).platformBrightness;
    bool isDarkMode = brightnessValue == Brightness.dark;
    SectionLessonProvider sectionLessonProvider =
        Provider.of<SectionLessonProvider>(context);
         final themeProvider = Provider.of<ThemeProvider>(context);

    Widget kemampuanDiraih(String title) {
      return Container(
        margin: EdgeInsets.only(bottom: 10),
        child: Row(
          children: [
            Icon(Icons.check,
                size: getProportionateScreenHeight(13), color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: Align(
                alignment: Alignment.topLeft,
                child: Text(
                  title,
                  style: thirdTextStyle.copyWith(
                    fontWeight: light,
                    color: Theme.of(context).colorScheme.onBackground,
                    fontSize: getProportionateScreenWidth(12),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }

    Widget persyaratan(String title) {
      return Container(
        margin: EdgeInsets.only(bottom: 10),
        child: Row(
          children: [
            title.isNotEmpty
                ? Icon(
                    Icons.brightness_1,
                    size: getProportionateScreenHeight(13),
                    color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                  )
                : SizedBox.shrink(),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: Align(
                alignment: Alignment.topLeft,
                child: Text(
                  title,
                  style: thirdTextStyle.copyWith(
                    fontWeight: light,
                    color: Theme.of(context).colorScheme.onBackground,
                    fontSize: getProportionateScreenWidth(12),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }

    return Consumer<DetailCourseProvider>(builder: (context, state, _) {
      if (state.state == ResultState.Loading) {
        return Center(
          child: CircularProgressIndicator(
            color: primaryColor,
            strokeWidth: 2,
          ),
        );
      } else if (state.state == ResultState.HasData) {
        var detailCourse = state.result!.data[0][0];
        print(detailCourse.outcome);
        print(detailCourse.requirement);

        List requirement;
        List outcomes = [];

        if (detailCourse.outcome != '') {
          outcomes = jsonDecode(detailCourse.outcome ?? 'gagal');
        }

        try {
          requirement = jsonDecode(detailCourse.requirement ?? '[]');
        } catch (e) {
          requirement = [];
        }

        final bool hasDescription = detailCourse.description!.isNotEmpty;
        return SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: getProportionateScreenHeight(9)),
                      Container(
                        margin: EdgeInsets.only(
                          left: getProportionateScreenWidth(10),
                          top: getProportionateScreenHeight(10),
                        ),
                        child: Text(
                          'Kursus Ini Sudah Termasuk',
                          style: thirdTextStyle.copyWith(
                            fontWeight: semiBold,
                            fontSize: getProportionateScreenWidth(14),
                          ),
                        ),
                      ),
                      SizedBox(height: 10),
                      KursusIncludeItems(
                          svg: 'assets/icons/clock.svg',
                          text:
                              '${detailCourse.totalDuration} video pembelajaran'),
                      KursusIncludeItems(
                          svg: 'assets/icons/lesson.svg',
                          text: '${detailCourse.totalLesson} pelajaran'),
                      KursusIncludeItems(
                          svg: 'assets/icons/calendar.svg',
                          text: 'Akses full seumur hidup'),
                      KursusIncludeItems(
                          svg: 'assets/icons/phone.svg',
                          text: ' Akses di ponsel dan TV '),
                    ],
                  ),
                ),
                SizedBox(
                  height: 5,
                ),
                ExpandableNotifier(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 12,
                      ),
                      Container(
                        margin: EdgeInsets.only(
                          left: getProportionateScreenWidth(10),
                          right: getProportionateScreenWidth(106),
                          bottom: getProportionateScreenWidth(8),
                        ),
                        child: Text('Kemampuan Yang Akan Diraih',
                            style: primaryTextStyle.copyWith(
                                fontWeight: semiBold,
                                letterSpacing: 1,
                                fontSize: getProportionateScreenWidth(14))),
                      ),
                      Expandable(
                        collapsed: ExpandableButton(
                          child: Container(
                            margin: EdgeInsets.only(
                                left: getProportionateScreenWidth(10)),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                outcomes.isEmpty
                                    ? Row(
                                        children: [
                                          Expanded(
                                            child: Align(
                                              alignment: Alignment.topLeft,
                                              child: Text(
                                                '',
                                              ),
                                            ),
                                          ),
                                        ],
                                      )
                                    : Column(children: [
                                        ...outcomes
                                            .map((e) => kemampuanDiraih(e))
                                            .take(2)
                                      ]),
                                if (outcomes.isNotEmpty && outcomes.length >= 3)
                                  SizedBox(height: 8),
                                if (outcomes.isNotEmpty && outcomes.length >= 3)
                                  Container(
                                    child: Text(
                                      "Tampilkan Lebih Banyak",
                                      style: primaryTextStyle.copyWith(
                                        fontWeight: semiBold,
                                        color: Theme.of(context).brightness ==
                                                Brightness.dark
                                            ? baruTextutih
                                            : fourthColor,
                                        fontSize:
                                            getProportionateScreenWidth(12),
                                      ),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        ),
                        expanded: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ExpandableButton(
                              child: Container(
                                margin: EdgeInsets.only(
                                    left: getProportionateScreenWidth(10)),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    outcomes.isEmpty
                                        ? Row(
                                            children: [
                                              Expanded(
                                                child: Align(
                                                  alignment: Alignment.topLeft,
                                                  child: Text(
                                                    '',
                                                  ),
                                                ),
                                              ),
                                            ],
                                          )
                                        : Column(
                                            children: outcomes
                                                .map((e) => kemampuanDiraih(e))
                                                .toList(),
                                          ),
                                    if (outcomes.isNotEmpty &&
                                        outcomes.length >= 3)
                                      SizedBox(
                                        height: 16,
                                      ),
                                    if (outcomes.isNotEmpty &&
                                        outcomes.length >= 3)
                                      Container(
                                        child: Text(
                                          "Tampilkan Lebih Sedikit",
                                          style: primaryTextStyle.copyWith(
                                            fontWeight: semiBold,
                                            color:
                                                Theme.of(context).brightness ==
                                                        Brightness.dark
                                                    ? baruTextutih
                                                    : fourthColor,
                                            fontSize:
                                                getProportionateScreenWidth(12),
                                          ),
                                        ),
                                      )
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                ExpandableNotifier(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 12,
                      ),
                      Container(
                        margin: EdgeInsets.only(
                          left: getProportionateScreenWidth(10),
                          right: getProportionateScreenWidth(106),
                          bottom: getProportionateScreenWidth(8),
                        ),
                        child: Text('Persyaratan',
                            style: primaryTextStyle.copyWith(
                                fontWeight: semiBold,
                                letterSpacing: 1,
                                fontSize: getProportionateScreenWidth(14))),
                      ),
                      Expandable(
                        collapsed: ExpandableButton(
                          child: Container(
                            margin: EdgeInsets.only(
                                left: getProportionateScreenWidth(10)),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                requirement.isEmpty
                                    ? Row(
                                        children: [
                                          Expanded(
                                            child: Align(
                                              alignment: Alignment.topLeft,
                                              child: Text(
                                                '',
                                              ),
                                            ),
                                          ),
                                        ],
                                      )
                                    : Column(children: [
                                        ...requirement
                                            .map((e) => persyaratan(e))
                                            .take(2)
                                      ]),
                                if (requirement.isNotEmpty &&
                                    requirement.length >= 3)
                                  SizedBox(height: 8),
                                if (requirement.isNotEmpty &&
                                    requirement.length >= 3)
                                  Container(
                                    child: Text(
                                      "Tampilkan Lebih Banyak",
                                      style: primaryTextStyle.copyWith(
                                        fontWeight: semiBold,
                                        color: Theme.of(context).brightness ==
                                                Brightness.dark
                                            ? baruTextutih
                                            : fourthColor,
                                        fontSize:
                                            getProportionateScreenWidth(12),
                                      ),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        ),
                        expanded: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ExpandableButton(
                              child: Container(
                                margin: EdgeInsets.only(
                                    left: getProportionateScreenWidth(10)),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    requirement.isEmpty
                                        ? Row(
                                            children: [
                                              Expanded(
                                                child: Align(
                                                  alignment: Alignment.topLeft,
                                                  child: Text(
                                                    '',
                                                  ),
                                                ),
                                              ),
                                            ],
                                          )
                                        : Column(
                                            children: requirement
                                                .map((e) => persyaratan(e))
                                                .toList(),
                                          ),
                                    if (requirement.isNotEmpty &&
                                        requirement.length >= 3)
                                      SizedBox(
                                        height: 16,
                                      ),
                                    if (requirement.isNotEmpty &&
                                        requirement.length >= 3)
                                      Container(
                                        child: Text(
                                          "Tampilkan Lebih Sedikit",
                                          style: primaryTextStyle.copyWith(
                                            fontWeight: semiBold,
                                            color:
                                                Theme.of(context).brightness ==
                                                        Brightness.dark
                                                    ? baruTextutih
                                                    : fourthColor,
                                            fontSize:
                                                getProportionateScreenWidth(12),
                                          ),
                                        ),
                                      )
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),

                SizedBox(height: getProportionateScreenHeight(5)),
                SizedBox(
                  height: 14,
                ),
                Align(
                  alignment: Alignment.topLeft,
                  child: Container(
                    margin:
                        EdgeInsets.only(left: getProportionateScreenWidth(10)),
                    child: Text(
                      'Deskripsi',
                      style: primaryTextStyle.copyWith(
                        fontWeight: semiBold,
                        letterSpacing: 1,
                        fontSize: getProportionateScreenWidth(14),
                      ),
                    ),
                  ),
                ),
                AnimatedSize(
                  curve: Curves.fastOutSlowIn,
                  duration: const Duration(milliseconds: 300),
                  child: detailCourse.description!.isNotEmpty
                      ? Container(
                          height: sectionLessonProvider.isExpanded ? 55 : null,
                          margin: EdgeInsets.symmetric(
                              horizontal: getProportionateScreenWidth(5)),
                          child: Html(
                            data: detailCourse.description!
                                .split('\n')
                                .take(2)
                                .join('\n'),
                            style: {
                              "body": Style(
                                fontSize:
                                    FontSize(getProportionateScreenWidth(12)),
                                fontWeight: FontWeight.bold,
                                fontFamily: 'Poppins',
                                textAlign: TextAlign.justify,
                                color: Theme.of(context).brightness ==
                                        Brightness.dark
                                    ? Colors.grey[100]
                                    : Colors.grey[600],
                              ),
                            },
                          ),
                        )
                      : SizedBox(),
                ),
                Padding(
                  padding:
                      EdgeInsets.only(left: getProportionateScreenWidth(3)),
                  child: detailCourse.description!.length > 140
                      ? TextButton(
                          style: TextButton.styleFrom(
                              foregroundColor: primaryColor),
                          onPressed: () => sectionLessonProvider.expanded(),
                          child: sectionLessonProvider.isExpanded
                              ? Text(
                                  'Tampilkan Lebih Banyak',
                                  style: primaryTextStyle.copyWith(
                                    fontWeight: semiBold,
                                    color: Theme.of(context).brightness ==
                                            Brightness.dark
                                        ? baruTextutih
                                        : fourthColor,
                                    fontSize: getProportionateScreenWidth(12),
                                  ),
                                  textAlign: TextAlign.left,
                                )
                              : Text(
                                  'Tampilkan Lebih Sedikit',
                                  style: primaryTextStyle.copyWith(
                                    fontWeight: semiBold,
                                    color: Theme.of(context).brightness ==
                                            Brightness.dark
                                        ? baruTextutih
                                        : fourthColor,
                                    fontSize: getProportionateScreenWidth(12),
                                  ),
                                ),
                        )
                      : SizedBox(),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (hasDescription &&
                        detailCourse.description!.length > 120)
                      SizedBox(height: getProportionateScreenHeight(10)),
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: getProportionateScreenWidth(10)),
                      child: Row(
                        children: [
                          CircleAvatar(
                            radius: 20,
                            backgroundColor: primaryColor,
                            backgroundImage: detailCourse.fotoProfile == null
                                ? AssetImage("assets/images/Profile Image.png")
                                : NetworkImage(detailCourse.fotoProfile!)
                                    as ImageProvider,
                          ),
                          SizedBox(width: getProportionateScreenWidth(10)),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                detailCourse.instructor ?? '',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(12),
                                  fontWeight: bold,
                                ),
                              ),
                              Row(
                                children: [
                                  Text(
                                    'Instructor, ',
                                    style: thirdTextStyle.copyWith(
                                      fontSize: getProportionateScreenWidth(10),
                                      fontWeight: light,
                                    ),
                                  ),
                                  Text(
                                    '${detailCourse.totalStudents ?? '0'} Murid, ',
                                    style: thirdTextStyle.copyWith(
                                      fontSize: getProportionateScreenWidth(10),
                                      fontWeight: light,
                                    ),
                                  ),
                                  Text(
                                    '${detailCourse.totalLesson ?? ''} Kursus',
                                    style: thirdTextStyle.copyWith(
                                      fontSize: getProportionateScreenWidth(10),
                                      fontWeight: light,
                                    ),
                                  )
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    // SizedBox(height: 2),
                    // widget.headline != null
                    //     ? Container(
                    //         margin: EdgeInsets.only(left: 10),
                    //         child: Text(
                    //           widget.headline!,
                    //           style: TextStyle(fontSize: 13),
                    //         ),
                    //       )
                    //     : const SizedBox.shrink(),
                    // Container(
                    //   margin: EdgeInsets.only(left: 10),
                    //   child: Row(
                    //     children: [
                    //       RatingBarIndicator(
                    //         itemSize: 11,
                    //         rating: double.parse(widget.rating ?? '0'),
                    //         direction: Axis.horizontal,
                    //         itemCount: 5,
                    //         itemBuilder: (context, _) => const FaIcon(
                    //           FontAwesomeIcons.solidStar,
                    //           color: Colors.amber,
                    //         ),
                    //       ),
                    //       SizedBox(width: 4),
                    //       Text(
                    //         double.parse(widget.rating ?? '0').toString(),
                    //         style: TextStyle(fontSize: 10),
                    //       ),
                    //       SizedBox(width: 4),
                    //       Text(
                    //         '(${widget.review ?? '0'})',
                    //         style: TextStyle(fontSize: 10),
                    //       ),
                    //     ],
                    //   ),
                    // ),
                    if (detailCourse.bio == null || detailCourse.bio!.isEmpty)
                      Padding(
                        padding: EdgeInsets.only(
                          left: getProportionateScreenHeight(10),
                          right: getProportionateScreenHeight(10),
                          bottom: getProportionateScreenHeight(10),
                        ),
                        child: const SizedBox(height: 10)
                      )
                    else
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(
                              left: getProportionateScreenWidth(5),
                              right: getProportionateScreenWidth(10),
                            ),
                            child: isExpanded2
                                ? Html(
                                    data: detailCourse.bio,
                                    style: {
                                      "body": Style(
                                        fontSize: FontSize(
                                            getProportionateScreenWidth(12)),
                                        fontWeight: light,
                                        fontFamily: 'Poppins',
                                      ),
                                    },
                                  )
                                : Html(
                                    data: detailCourse.bio != null &&
                                            detailCourse.bio!.length > 100
                                        ? detailCourse.bio!.substring(0, 200)
                                        : detailCourse.bio!,
                                    style: {
                                      "body": Style(
                                        fontSize: FontSize(
                                            getProportionateScreenWidth(12)),
                                        fontWeight: reguler,
                                        fontFamily: 'Poppins',
                                      ),
                                    },
                                  ),
                          ),
                          if (detailCourse.bio!.isNotEmpty &&
                              detailCourse.bio!.length > 100)
                            Padding(
                              padding: EdgeInsets.only(
                                left: getProportionateScreenWidth(12),
                                bottom: getProportionateScreenHeight(10),
                              ),
                              child: GestureDetector(
                                onTap: () {
                                  setState(() {
                                    isExpanded2 = !isExpanded2;
                                    print('asdasd');
                                  });
                                },
                                child: Text(
                                  isExpanded2
                                      ? 'Tampilkan Lebih Sedikit'
                                      : 'Tampilkan Lebih Banyak',
                                  style: thirdTextStyle.copyWith(
                                    fontWeight: semiBold,
                                    color: Theme.of(context).brightness ==
                                            Brightness.dark
                                        ? baruTextutih
                                        : fourthColor,
                                    fontSize: getProportionateScreenWidth(12),
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                  ],
                ),
                // Instruktur(
                //   id: detailCourse.instructorId ?? '1',
                //   bio: detailCourse.bio,
                //   instructor: detailCourse.instructor,
                //   rating: detailCourse.rating[0].avgRating.toString(),
                //   review: detailCourse.rating[0].totalReview ?? '',
                //   fotoProfile: detailCourse.fotoProfile,
                //   totalLesson: detailCourse.totalLesson,
                //   totalStudent: detailCourse.totalStudents,
                //   headline: detailCourse.headlineInstructor,
                // ),
              ],
            ),
          ),
        );
      } else if (state.state == ResultState.Error) {
        return Center(
          child: Text('Terjadi Kesalahan'),
        );
      } else {
        return Center(child: Text('error'));
      }
    });
  }
}
