import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'dart:ui' as ui;
import 'package:intl/intl.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/mycar/car_details_page.dart';
import 'package:road24_mobile/view/mycar/my_car_page.dart';
import '../my_app.dart';

class FrequentWidgets {
  static Future capture(GlobalKey? key) async {
    if (key == null) return null;
    RenderRepaintBoundary boundary =
        key.currentContext?.findRenderObject() as RenderRepaintBoundary;
    final image = await boundary.toImage(pixelRatio: 3);
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    final pngBytes = byteData?.buffer.asUint8List();

    return pngBytes;
  }

  static String intComma(dynamic number, {decimalDigit = 2}) {
    final formatCurrency = NumberFormat.currency(
        locale: "en_US", symbol: "", decimalDigits: decimalDigit);
    return formatCurrency.format(number).toString().replaceAll(",", " ");
  }

  static String cardNumberFormat(String number) {
    return number.substring(0, 4) + " **** **** " + number.substring(12);
  }

  static Future<String> getDeviceId() async {
    var deviceId = await FlutterUdid.udid;

    print("device id....$deviceId");

    await MyApp.preferences?.setDeviceId(deviceId);

    return deviceId;
  }

  static String textForFineStatusId(context, int? pStatus) {
    switch (pStatus) {
      case 1:
        return S.of(context).fine_status_1;
      case 2:
        return S.of(context).fine_status_2;
      case 3:
        return S.of(context).fine_status_3;
      case 4:
        return S.of(context).fine_status_4;
      case 5:
        return S.of(context).fine_status_5;
    }
    return "";
  }

  static String dateTimeToLocal(String date) {
    if (Config.language == "oz")
      return DateFormat('dd-MMM yyyy, HH:mm', 'uz')
          .format(DateTime.parse(date).toLocal())
          .toString();

    return DateFormat('dd-MMM yyyy, HH:mm', Config.language)
        .format(DateTime.parse(date).toLocal())
        .toString();
  }

  static Widget createTabForMain(String text, bool isActive) {
    return Tab(
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 5.0),
        padding: const EdgeInsets.symmetric(horizontal: 15.0),
        decoration: BoxDecoration(
          color: isActive ? Colors.white : Colors.transparent,
          borderRadius: BorderRadius.circular(100.0),
        ),
        child: Center(
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 4),
            child: Text(
              text,
              style: TextStyle(
                color: isActive ? Color(0xff000000) : Color(0xff747474),
                fontWeight: isActive ? FontWeight.w600 : FontWeight.w500,
                fontSize: 15.0,
                height: 1.2,
                letterSpacing: 0.2,
              ),
              maxLines: 1,
            ),
          ),
        ),
      ),
    );
  }

  static 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;
  }

  static appBarBackButton(context) {
    return Material(
      type: MaterialType.transparency,
      child: InkWell(
        onTap: () {
          try {
            Navigator.pop(context);
          } catch (e) {}
        },
        child: Container(
          margin: const EdgeInsets.all(10.0),
          decoration: BoxDecoration(
            color: Color(0xffDFDFDF),
            shape: BoxShape.circle,
          ),
          child: const Center(
            child: Icon(
              Icons.arrow_back_ios_outlined,
              size: 20.0,
              color: Colors.black,
            ),
          ),
        ),
      ),
    );
  }

  static void carNeedToRefresh() {
    MyCarPage.needToRefresh.value = true;

    if (!MyCarPage.carPageNotifierDisposed)
      CarDetailsPage.refreshPage.value = true;
  }

  static String getTextConcat(String text) {
    var language = Config.language;

    return "${text}_$language";
  }

  static String calculateTimeDifferenceBetween(context,
      {required String startDateStr, required DateTime endDate}) {
    var startDate = DateTime.parse(startDateStr);

    int seconds = endDate.difference(startDate).inSeconds;

    if (seconds < 60)
      return S.of(context).now;
    else if (seconds >= 60 && seconds < 3600)
      return '${startDate.difference(endDate).inMinutes.abs()} ${S.of(context).minuteAgo}';
    else if (seconds >= 3600 && seconds < 86400)
      return '${startDate.difference(endDate).inHours.abs()} ${S.of(context).hourAgo}';
    else {
      var dayDifference = startDate.difference(endDate).inDays.abs();

      var language = Config.language;

      if (language == "ru") {
        switch (dayDifference) {
          case 1:
            return "1 день назад";
          case 2:
          case 3:
          case 4:
            return "$dayDifference дня назад";
        }
      }

      if (dayDifference > 31) {
        return startDateStr.toFormatDate()!;
      }

      return '${startDate.difference(endDate).inDays.abs()} ${S.of(context).dayAgo}';
    }
  }
}
