import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:road24_mobile/data/response/CarsResponse.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/mycar/add/confident_page.dart';
import 'package:road24_mobile/view/mycar/add/inspection/inspection_page.dart';
import 'package:road24_mobile/view/mycar/add/insurance_page.dart';
import 'package:road24_mobile/view/mycar/add/oil_page_new.dart';
import 'package:road24_mobile/view/mycar/add/tinting_page.dart';
import 'package:road24_mobile/view/mycar/fines/fines_page.dart';

class CarDetails extends StatelessWidget {
  final Results? carDetails;
  final bool isFromMainPage;
  const CarDetails({this.carDetails, this.isFromMainPage = true});

  String _humanizeCost(String sum) {
    if (sum.endsWith('.0')) {
      sum = sum + '0';
    }
    List<String> sumBuffer = sum.split('.');
    String refactoredSumFormat =
        FrequentWidgets.intComma(int.parse(sumBuffer[0])).replaceAll(',', ' ') +
            '.' +
            sumBuffer[1].toString();
    refactoredSumFormat = refactoredSumFormat.replaceAll(".00", "");
    return refactoredSumFormat;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          _widgetFines(context),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(child: _widgetInsurance(context)),
              const SizedBox(width: 12),
              Expanded(child: _widgetInspection(context)),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(child: _widgetConfidant(context)),
              const SizedBox(width: 12),
              Expanded(child: _widgetTinting(context)),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(child: _widgetOil(context)),
              const SizedBox(width: 12),
              Expanded(child: SizedBox()),
            ],
          ),
        ],
      ),
    );
  }

  Widget _widgetFines(BuildContext context) {
    if (carDetails == null) return _WidgetPlaceHolder(height: 167);
    return GestureDetector(
      onTap: () async {
        await Navigator.push(
          context,
          CupertinoPageRoute(builder: (context) => FinesPage()),
        );

        enableRefreshingPage();
      },
      child: Container(
        width: double.infinity,
        height: 155.0,
        padding: EdgeInsets.all(6.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(
            color: (carDetails!.finesCount == 0)
                ? Colors.transparent
                : AppColors.error,
          ),
          borderRadius: BorderRadius.circular(12.0),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.all(6.0),
              decoration: BoxDecoration(
                color: Color(0xffE9E9E9),
                shape: BoxShape.circle,
              ),
              child: SvgPicture.asset(
                "assets/svg/fine_icon.svg",
                height: 19.0,
                width: 19.0,
                color: (carDetails!.finesCount == 0)
                    ? Color(0xff929292)
                    : AppColors.error,
              ),
              margin: const EdgeInsets.symmetric(vertical: 6.0),
            ),
            AutoSizeText(
              S.of(context).fines,
              style: AppStyle.textStyle().copyWith(
                color: Color(0xff747474),
                fontSize: 18.0,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            (carDetails!.finesCount == 0)
                ? Expanded(
                    child: AutoSizeText(
                      S.of(context).all_is_good,
                      style: AppStyle.textStyle().copyWith(
                        color: Color(0xffADADAD),
                        fontSize: 20.0,
                        fontWeight: FontWeight.w500,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 4,
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                : Expanded(
                    child: AutoSizeText(
                      "${_humanizeCost(carDetails!.finesRemain.toString())} ${S.of(context).uzs.toLowerCase()}",
                      style: AppStyle.textStyle().copyWith(
                        color: Color(0xff282828),
                        fontSize: 22.0,
                        fontWeight: FontWeight.w600,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
            (carDetails!.finesCount == 0)
                ? Expanded(
                    child: AutoSizeText(
                      S.of(context).no_fine,
                      style: AppStyle.textStyle().copyWith(
                        color: Color(0xffADADAD),
                        fontSize: 13.0,
                        fontWeight: FontWeight.w500,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 4,
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                : SizedBox(),
            (carDetails!.finesCount == 0)
                ? SizedBox(height: 2.0)
                : Expanded(
                    child: AutoSizeText(
                      S.of(context).nFines(carDetails!.finesCount),
                      style: AppStyle.textStyle().copyWith(
                        color: Color(0xffF51A51),
                        fontSize: 18.0,
                        fontWeight: FontWeight.w500,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 4,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
          ],
        ),
      ),
    );
  }

  Widget _widgetInsurance(BuildContext context) {
    if (carDetails == null) return const _WidgetPlaceHolder(height: 155);
    return _WidgetItem(
      iconName: "insurance_icon",
      onTap: () async {
        await Navigator.push(
          context,
          CupertinoPageRoute(
            builder: (context) => InsurancePage(
              insurance: carDetails!.insurance,
            ),
          ),
        );
        enableRefreshingPage();
      },
      title: S.of(context).insurance,
      description: AutoSizeText(
        S.of(context).if_no_info_in_car_element,
        style: AppStyle.textStyle().copyWith(
          color: Color(0xff747474),
          fontSize: 13.0,
          fontWeight: FontWeight.w500,
        ),
      ),
      datePassed: carDetails?.insurance?.datePassed,
      dateEnd: carDetails?.insurance?.dateEnd,
      visibleAdd: carDetails!.insurance == null,
    );
  }

  Widget _widgetInspection(BuildContext context) {
    if (carDetails == null) return const _WidgetPlaceHolder(height: 155);
    return _WidgetItem(
      iconName: "texosmotr_icon",
      onTap: () async {
        await Navigator.push(
          context,
          CupertinoPageRoute(builder: (context) {
            final inspection = carDetails!.inspection;
            if (inspection != null)
              return InspectionPage(
                id: inspection.id,
                carId: carDetails!.carDetail,
                datePassed: inspection.datePassed,
                dateEnd: inspection.dateEnd,
                pDivision: inspection.pDivision,
              );
            return InspectionPage(carId: carDetails!.carDetail);
          }),
        );
        enableRefreshingPage();
      },
      title: S.of(context).technical_inspection,
      description: AutoSizeText(
        S.of(context).if_no_info_in_car_inspection,
        style: AppStyle.textStyle().copyWith(
          color: AppColors.colorf51a51,
          fontSize: 13.0,
          fontWeight: FontWeight.w500,
        ),
      ),
      datePassed: carDetails?.inspection?.datePassed,
      dateEnd: carDetails?.inspection?.dateEnd,
      visibleAdd: false,
    );
  }

  Widget _widgetConfidant(BuildContext context) {
    if (carDetails == null) return const _WidgetPlaceHolder(height: 155);
    return _WidgetItem(
      iconName: "insurance_icon",
      onTap: () async {
        await Navigator.push(
          context,
          CupertinoPageRoute(
            builder: (context) => ConfidentPage(
              confidant: carDetails!.confidant,
            ),
          ),
        );

        enableRefreshingPage();
      },
      title: S.of(context).confidant,
      description: AutoSizeText(
        S.of(context).if_no_info_in_car_element,
        style: AppStyle.textStyle().copyWith(
          color: Color(0xff747474),
          fontSize: 13.0,
          fontWeight: FontWeight.w500,
        ),
      ),
      datePassed: carDetails?.confidant?.datePassed,
      dateEnd: carDetails?.confidant?.dateEnd,
      visibleAdd: carDetails!.confidant == null,
    );
  }

  Widget _widgetTinting(BuildContext context) {
    if (carDetails == null) return const _WidgetPlaceHolder(height: 155);
    return _WidgetItem(
      iconName: "tinting_icon",
      onTap: () async {
        await Navigator.push(
          context,
          CupertinoPageRoute(
            builder: (context) => TintingPage(
              askingFirstTime: false,
              tinting: carDetails!.tinting,
            ),
          ),
        );

        enableRefreshingPage();
      },
      title: S.of(context).tinting,
      description: AutoSizeText(
        S.of(context).if_no_info_in_car_element,
        style: AppStyle.textStyle().copyWith(
          color: Color(0xff747474),
          fontSize: 13.0,
          fontWeight: FontWeight.w500,
        ),
      ),
      datePassed: carDetails?.tinting?.datePassed,
      dateEnd: carDetails?.tinting?.dateEnd,
      visibleAdd: carDetails!.tinting == null,
    );
  }

  Widget _widgetOil(BuildContext context) {
    if (carDetails == null) return const _WidgetPlaceHolder(height: 155);
    return _WidgetItem(
      iconName: "oil_icon",
      onTap: () async {
        await Navigator.push(
          context,
          CupertinoPageRoute(builder: (_) {
            // return OilListPage(carDetailId: carDetails!.id);
            return OilPage(oil: carDetails!.oil);
          }),
        );
        enableRefreshingPage();
      },
      title: S.of(context).oil,
      description: AutoSizeText(
        S.of(context).if_no_info_in_car_element,
        style: AppStyle.textStyle().copyWith(
          color: Color(0xff747474),
          fontSize: 13.0,
          fontWeight: FontWeight.w500,
        ),
      ),
      datePassed: carDetails?.oil?.lastReplacement,
      dateEnd: carDetails?.oil?.nextReplacement,
      visibleAdd: carDetails!.oil == null,
    );
  }

  enableRefreshingPage() {
    FrequentWidgets.carNeedToRefresh();
    // MyCarPage.needToRefresh.value = true;
  }
}

class _WidgetItem extends StatelessWidget {
  final String title;
  final Widget description;
  final String? datePassed;
  final String? dateEnd;
  final bool visibleAdd;
  final GestureTapCallback? onTap;
  final String iconName;

  const _WidgetItem({
    required this.title,
    required this.description,
    required this.iconName,
    this.datePassed,
    this.dateEnd,
    this.visibleAdd = true,
    this.onTap,
  });

  svgAsset(String svgName) {
    return Container(
      padding: const EdgeInsets.all(6.0),
      decoration: const BoxDecoration(
        color: Color(0xffE9E9E9),
        shape: BoxShape.circle,
      ),
      child: SvgPicture.asset("assets/svg/$svgName.svg",
          height: 18.0, width: 18.0),
      margin: const EdgeInsets.symmetric(vertical: 6.0),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Container(
        height: 155.0,
        padding: const EdgeInsets.all(6.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.0),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                svgAsset(iconName),
                if (visibleAdd)
                  SvgPicture.asset('assets/svg/add.svg', width: 19.0)
              ],
            ),
            AutoSizeText(
              title,
              style: AppStyle.textStyle().copyWith(
                color: Color(0xff747474),
                fontSize: 18.0,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            _widgetDescription(context),
          ],
        ),
      ),
    );
  }

  Widget _widgetDescription(BuildContext context) {
    DateTime? dDatePassed;
    DateTime? dDateEnd;
    String? datePassedFormat;
    String? dateEndFormat;

    if (datePassed != null) {
      dDatePassed = DateTime.tryParse(datePassed!)?.toLocal();
    }
    if (dateEnd != null) {
      dDateEnd = DateTime.tryParse(dateEnd!)?.toLocal();
    }
    if (dDatePassed != null) {
      datePassedFormat = dDatePassed.dateToStr();
      // DateFormat(
      //   'dd-MMM yyyy',
      //   Config.language.replaceAll('oz', 'uz'),
      // ).format(dDatePassed);
      if (Config.language == 'uz')
        datePassedFormat = datePassedFormat.toKrill();
    }
    if (dDateEnd != null) {
      dateEndFormat = dDateEnd.dateToStr();
      // DateFormat(
      //   'dd-MMM yyyy',
      //   Config.language.replaceAll('oz', 'uz'),
      // ).format(dDateEnd);
      if (Config.language == 'uz') dateEndFormat = dateEndFormat.toKrill();
    }

    if (dDateEnd != null && dDateEnd.isBefore(DateTime.now())) {
      return _widgetExpired(context, dateEndFormat);
    }

    if (dDateEnd != null && dDatePassed != null) {
      return _widgetHasTime(context, dateEndFormat, dDatePassed, dDateEnd);
    }

    return Padding(padding: const EdgeInsets.only(top: 4), child: description);
  }

  Widget _widgetHasTime(
    BuildContext context,
    String? dateEndFormat,
    DateTime datePassed,
    DateTime dateEnd,
  ) {
    final totalDays = datePassed.difference(dateEnd).inDays;
    final passedDays = datePassed.difference(DateTime.now()).inDays;
    final lessTime = dateEnd.difference(DateTime.now()).inDays <= 60;
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        AutoSizeText(
          S.of(context).nDays(dateEnd.difference(DateTime.now()).inDays),
          style: AppStyle.textStyle().copyWith(
            color: Color(0xff282828),
            fontSize: 20.0,
            fontWeight: FontWeight.w500,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 4),
        ClipRRect(
          borderRadius: BorderRadius.circular(3),
          child: LinearProgressIndicator(
            backgroundColor: Color(0xFFE9E9E9),
            valueColor: AlwaysStoppedAnimation(
              lessTime ? AppColors.error : AppColors.indicatorColor,
            ),
            value: passedDays / totalDays,
            minHeight: 5.0,
          ),
        ),
        const SizedBox(height: 4),
        AutoSizeText(
          "$dateEndFormat",
          style: AppStyle.textStyle().copyWith(
            color: lessTime ? AppColors.error : Color(0xff747474),
            fontSize: 13.0,
            fontWeight: FontWeight.w500,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  Widget _widgetExpired(BuildContext context, String? dateEndFormat) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        AutoSizeText(
          S.of(context).expired,
          style: AppStyle.textStyle().copyWith(
            color: AppColors.error,
            fontSize: 20.0,
            fontWeight: FontWeight.w500,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 4),
        ClipRRect(
          borderRadius: BorderRadius.circular(3),
          child: LinearProgressIndicator(
            backgroundColor: Color(0xFFE9E9E9),
            valueColor: const AlwaysStoppedAnimation(AppColors.error),
            value: 1,
            minHeight: 5.0,
          ),
        ),
        const SizedBox(height: 4),
        AutoSizeText(
          "$dateEndFormat",
          style: AppStyle.textStyle().copyWith(
            color: AppColors.colorf51a51,
            fontSize: 13.0,
            fontWeight: FontWeight.w500,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }
}

class _WidgetPlaceHolder extends StatelessWidget {
  final double? width;
  final double? height;

  const _WidgetPlaceHolder({this.width, this.height});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      padding: const EdgeInsets.all(6.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                height: 40.0,
                width: 40.0,
                decoration: BoxDecoration(
                  color: AppColors.colorcacaca.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12.0),
                ),
              ),
              Container(
                height: 30.0,
                width: 30.0,
                decoration: BoxDecoration(
                  color: AppColors.colorcacaca.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12.0),
                ),
              ),
            ],
          ),
          const SizedBox(height: 4.0),
          Container(
            height: 15.0,
            width: 100.0,
            decoration: BoxDecoration(
              color: AppColors.colorcacaca.withOpacity(0.2),
              borderRadius: BorderRadius.circular(12.0),
            ),
          ),
          const SizedBox(height: 10.0),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 8.0,
                width: 150.0,
                decoration: BoxDecoration(
                  color: AppColors.colorcacaca.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12.0),
                ),
              ),
              const SizedBox(height: 10.0),
              Container(
                height: 8.0,
                width: 120.0,
                decoration: BoxDecoration(
                  color: AppColors.colorcacaca.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12.0),
                ),
              ),
              const SizedBox(height: 12.0),
              Container(
                height: 8.0,
                width: 80.0,
                decoration: BoxDecoration(
                  color: AppColors.colorcacaca.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12.0),
                ),
              ),
            ],
          ),
          const SizedBox(height: 4.0),
        ],
      ),
    );
  }
}
