import 'dart:convert';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;
import 'lat_lng.dart';
import 'place.dart';
import 'uploaded_file.dart';
import '/backend/schema/enums/enums.dart';
import '/auth/custom_auth/auth_util.dart';

String formatDate(String date) {
  DateTime parseDate = DateTime.parse(date);
  DateFormat format = DateFormat('yyyy/MM/dd');
  String formatedDate = format.format(parseDate);
  return formatedDate;
}

String? convertToUpperCase(String? text) {
  // Check if the input text is not null before converting to uppercase
  if (text != null && text.isNotEmpty) {
    List<String> words = text.split(' ');
    for (int i = 0; i < words.length; i++) {
      String word = words[i];
      if (word.isNotEmpty) {
        words[i] = word[0].toUpperCase() + word.substring(1);
      }
    }
    return words.join(' ');
  } else {
    return null; // or return an empty string, depending on your use case
  }
}

String? positionLabel(String? position) {
  switch (position) {
    //data to label
    case 'director':
      return 'Director';
    case 'shareholder':
      return 'Shareholder';
    case 'company_secretary':
      return 'Company Secretary';
    //label to data
    case 'Director':
      return 'director';
    case 'Shareholder':
      return 'shareholder';
    case 'Company Secretary':
      return 'company_secretary';
    default:
      return position; // return the original value if not recognized
  }
}

String formatTime(String timestamp) {
  // Parse the timestamp
  DateTime dateTime = DateTime.parse(timestamp).toLocal();

  // Convert to the desired format (9:54)
  String formattedTime = DateFormat.Hm().format(dateTime);

  return formattedTime;
}

bool comparePermission(
  List<int> getPermissionID,
  int permissionID,
) {
  // Function definition
  bool isIntInList(int target, List<int> intList) {
    return intList.contains(target);
  }

  int myTargetInt = permissionID;
  List<int> myIntList = getPermissionID;

// Check if the list is empty, trigger an alert or return a different value
  if (myIntList.isEmpty) {
    // Trigger an alert or return a different value
    // You can replace the following line with your alert logic or different return value
    print('Alert: The permission list is empty!');
    return false;
  }

  return isIntInList(myTargetInt, myIntList);
}

String formatDate2(String date) {
  DateTime parseDate = DateTime.parse(date);
  DateFormat format = DateFormat('yyyyMMdd');
  String formatedDate = format.format(parseDate);
  return formatedDate;
}

String getCategoryLabel(int categoryId) {
  String label;
  switch (categoryId) {
    case 1:
      label = 'Bank Statement';
      break;
    case 2:
      label = 'Income';
      break;
    case 3:
      label = 'Expense';
      break;
    case 4:
      label = 'Others';
      break;
    case 5:
      label = 'Income Tax Statement';
      break;
    default:
      label =
          'Unknown Category'; // Default label if category ID doesn't match any case
      break;
  }
  return label;
}

Color getStatusColor(String status) {
  switch (status) {
    case "uploaded":
    case "in_progress":
      return Colors.white;
    case "ocr_complete":
      return Color(0xFFFFEFBD); // Yellow color for "ocr_complete"
    case "failed":
      return Color(0xFFF5AE97); // Red color for "failed"
    default:
      return Colors.white; // Default color if status doesn't match any case
  }
}

List<String> filteredRemovePermissions(
  List<String>? addPermissions,
  List<String>? removePermissions,
) {
  if (addPermissions == null || removePermissions == null) {
    // Handle the case where one or both lists are null
    return [];
  }

  // Create sets for faster lookup
  Set<String> addSet = Set<String>.from(addPermissions);
  Set<String> removeSet = Set<String>.from(removePermissions);

  // Find the differing values
  List<String> differingValues = removeSet.difference(addSet).toList();

  // Print the differing values (you can replace this with your desired logic)
  print('Differing values: $differingValues');

  return differingValues;
}

List<dynamic> extractStatus(String jsonData) {
  try {
    final Map<String, dynamic> data = jsonDecode(jsonData);

    if (data.containsKey('documents') && data['documents'] is List) {
      List<dynamic> documents = data['documents'];

      // Filter the documents with 'completed' status
      List<Map<String, dynamic>> completedDocuments = documents
          .whereType<Map<String, dynamic>>()
          .where((doc) => doc['status'] == 'completed')
          .toList();

      // Extract necessary information
      List<dynamic> extractedData = completedDocuments.map((doc) {
        return {
          'Category ID': doc['bookkeeping_document_category_id'],
          'URL': doc['url'],
          'Created At': doc['created_at']
        };
      }).toList();

      return extractedData;
    } else {
      print('Invalid JSON format or missing "documents" key.');
      return []; // Return an empty list if data is not as expected
    }
  } catch (e) {
    print('Error: $e');
    return []; // Return an empty list in case of an error
  }
}

String getStatus2(String status) {
  switch (status) {
    case "uploaded":
      return 'Uploaded'; // Blue color for "Uploaded"
    case "in_progress":
      return 'In progress'; // Blue color for "In progress"
    case "ocr_complete":
      return 'OCR complete'; // Yellow color for "OCR complete"
    case "failed":
      return 'Failed'; // Red color for "Failed"
    default:
      return '::0xFFFFFFFF'; // Default color if status doesn't match any case (white color)
  }
}

List<String> addAccessRightPrefix(List<dynamic> roles) {
  List<String> result = [];

  for (String item in roles) {
    String newItem = "Access right : $item";
    result.add(newItem);
  }

  return result;
}
