import 'package:didvan/config/design_config.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:persian_datetime_picker/persian_datetime_picker.dart';

import '../models/day_time.dart';

class DateTimeUtils {
  static DayTime handleDayTime(String dayTime) {
    DateFormat format = DateFormat("HH:mm");
    DateTime dateTime = format.parse(dayTime);
    int selectedTimeHour = dateTime.hour;
    String selectedTimeMinute = dateTime.minute.toString();
    Meridiem selectedMeridiem = Meridiem.AM;

    if (selectedTimeHour > 12) {
      selectedTimeHour -= 12;
      selectedMeridiem = Meridiem.PM;
    } else if (selectedTimeHour == 0) {
      selectedTimeHour = 24;
      selectedMeridiem = Meridiem.AM;
    }
    return DayTime(
        hour: selectedTimeHour.toString(),
        minute: selectedTimeMinute,
        meridiem: selectedMeridiem);
  }

  static String handleDayTimeReverse(DayTime dayTime) {
    String h = dayTime.hour;
    String m = dayTime.minute.padLeft(2, "0");
    if (dayTime.meridiem == Meridiem.PM) {
      h = (int.parse(h) + 12).toString().padLeft(2, "0");
    }

    return "$h:$m";
  }

  static TimeOfDay stringToTimeOfDay(String input) => TimeOfDay(
        hour: int.parse(input.split(':')[0]),
        minute: int.parse(input.split(':')[1]),
      );

  static String normalizeTimeDuration(Duration input) {
    String minute;
    String second;

    if (input.inMinutes < 10) {
      minute = '0${input.inMinutes}';
    } else {
      minute = input.inMinutes.toString();
    }
    int realSeconds = input.inSeconds % 60;
    if (realSeconds < 10) {
      second = '0$realSeconds';
    } else {
      second = (realSeconds).toString();
    }
    return '$minute:$second';
  }

  static Future<String?> showDatePicker({
    String? initialDate,
    String? startDate,
    String? endDate,
  }) async {
    final initDate = initialDate == null ? null : DateTime.parse(initialDate);
    final initialJalali = Jalali.fromDateTime(initDate ?? DateTime.now());

    final firstDate = Jalali.fromDateTime(
      startDate == null ? DateTime(2021) : DateTime.parse(startDate),
    );

    final lastDate = Jalali.fromDateTime(
      endDate == null ? DateTime.now() : DateTime.parse(endDate),
    );

    final Jalali? result = await showPersianDatePicker(
      context: DesignConfig.context!,
      initialDate: initialJalali,
      firstDate: firstDate,
      lastDate: lastDate,
      builder: (context, child) => Theme(
        data: Theme.of(context).copyWith(
            textTheme: Theme.of(context).textTheme.copyWith(
                headlineMedium: Theme.of(context).textTheme.displaySmall)),
        child: child!,
      ),
    );

    return result?.toDateTime().toString();
  }

  static Future<String?> showCupertinoDatePicker({
    String? initialDate,
    String? startDate,
    String? endDate,
  }) async {
    final initDate = initialDate == null ? null : DateTime.parse(initialDate);
    final initialJalali = Jalali.fromDateTime(initDate ?? DateTime.now());

    final firstDate = Jalali.fromDateTime(
      startDate == null ? DateTime(2021) : DateTime.parse(startDate),
    );

    final lastDate = Jalali.fromDateTime(
      endDate == null ? DateTime.now() : DateTime.parse(endDate),
    );

    final Jalali? result = await showPersianDatePicker(
      context: DesignConfig.context!,
      initialDate: initialJalali,
      firstDate: firstDate,
      lastDate: lastDate,
      builder: (context, child) => Theme(
        data: Theme.of(context).copyWith(
            textTheme: Theme.of(context).textTheme.copyWith(
                headlineMedium: Theme.of(context).textTheme.displaySmall)),
        child: child!,
      ),
    );

    return result?.toDateTime().toString();
  }

  static String timeWithAmPm(String input) {
    try {
      final dateTime = utcToLocalTime(input);
      bool isAm = true;
      int hour = 0;
      int minute = 0;
      if (dateTime.hour > 12) {
        isAm = false;
        hour = dateTime.hour - 12;
      } else {
        hour = dateTime.hour;
      }
      minute = dateTime.minute;
      return '$hour:${_timeNormalizer(minute)} ${isAm ? 'ق.ظ' : 'ب.ظ'}';
    } catch (e) {
      return '';
    }
  }

  static DateTime utcToLocalTime(String input) {
    final dateTime = DateTime.parse(input);
    return dateTime.add(const Duration(hours: 3, minutes: 30));
  }

  static String _timeNormalizer(int input) {
    if (input < 10) return '0$input';
    return input.toString();
  }

  static String momentGenerator(String input) {
    final date = DateTime.parse(input);
    final int seconds = (DateTime.now().difference(date).inSeconds).floor();

    double interval = seconds / 31536000;

    if (interval > 1) {
      return "در ${interval.floor()} سال پیش";
    }
    interval = seconds / 2592000;
    if (interval > 1) {
      return "در ${interval.floor()} ماه پیش";
    }
    interval = seconds / 86400;
    if (interval > 1) {
      if (interval.floor() == 1) return 'دیروز';
      return "در ${interval.floor()} روز پیش";
    }
    interval = seconds / 3600;
    if (interval > 1) {
      return "در ${interval.floor()} ساعت پیش";
    }
    interval = seconds / 60;
    if (interval > 1) {
      return "در ${interval.floor()} دقیقه پیش";
    }
    return 'هم اکنون';
    // return seconds.floor().toString() + " ثانیه پیش";
  }
}