import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
import { Issues, flatten } from 'valibot'

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

export const valiError = (issues: Issues) => {
  const errors = flatten(issues).nested
  const valiErrors: Record<string, string | null> = Object
    //
    .keys(errors)
    .reduce((prev, curr) => ({ ...prev, [curr]: errors[curr]?.at(-1) }), {})

  return valiErrors
}

export function calculateProfileCompletion(userInfo: any) {
  const mandatoryFields = [
    'firstName',
    'lastName',
    'countryOfResidence',
    'phone',
    'languagesSpoken',
    'role',
  ]
  const optionalFields = Object.keys(userInfo).filter(
    (key) =>
      !mandatoryFields.includes(key) &&
      key !== 'id' &&
      key !== 'createdAt' &&
      userInfo[key] != null &&
      userInfo[key] !== ''
  )

  let completion = 0

  // Calculate mandatory fields completion
  mandatoryFields.forEach((field) => {
    if (
      userInfo[field] &&
      (field !== 'languagesSpoken' || userInfo[field].length > 0)
    ) {
      completion += 10 // Each mandatory field contributes 10%
    }
  })

  // Calculate optional fields completion
  const optionalCompletion =
    (optionalFields.length /
      (Object.keys(userInfo).length - mandatoryFields.length - 2)) *
    40 // -2 to exclude 'id' and 'createdAt'
  completion += optionalCompletion

  // Round the completion percentage to the nearest whole number
  return Math.round(completion)
}

// Function to determine the color based on the completion percentage
export function determineProgressBarColor(completion: any) {
  if (completion < 33) {
    return 'red' // Less than 33% complete
  } else if (completion < 66) {
    return 'orange' // Between 33% and 66% complete
  } else {
    return '#4ff549' // More than 66% complete
  }
}

/// This function now returns only the embed URL for a video based on its platform
export const getVideoEmbedUrl = (url: string) => {
  if (!url) return null

  // YouTube URL patterns
  if (url.match(/(youtube.com|youtu.be)/)) {
    const videoId = url.split(/v=|\/v\/|youtu\.be\//)[1].split(/[?&]/)[0]
    return `https://www.youtube.com/embed/${videoId}`
  }

  // Vimeo URL pattern
  else if (url.match(/vimeo.com/)) {
    const videoId = url.split('/').pop()
    return `https://player.vimeo.com/video/${videoId}`
  }

  // DailyMotion URL pattern
  else if (url.match(/dailymotion.com/)) {
    const videoId = url.split('/video/')[1].split(/[?&]/)[0]
    return `https://www.dailymotion.com/embed/video/${videoId}`
  }

  // TikTok URL pattern
  // else if (url.match(/tiktok.com/)) {
  //   // Note: Direct embedding of TikTok videos like this may not be straightforward due to their embedding mechanism
  //   // It's recommended to use TikTok's oEmbed API for a more reliable solution
  //   // This function would need to handle TikTok URLs differently, potentially requiring server-side processing to fetch the embed code
  //   console.warn(
  //     'Direct TikTok video embedding might require additional handling.'
  //   )
  //   return null // Placeholder as direct embedding might not be supported
  // }

  // Return null if no matching pattern or unsupported platform
  return null
}

export const calculateDuration = (
  startDate: Date | undefined,
  endDate?: Date,
  isCurrent: boolean = false,
  showMonths: boolean = false
): string => {
  if (!startDate) return '';

  const start = new Date(startDate);
  const end = isCurrent ? new Date() : endDate ? new Date(endDate) : new Date();

  if (isNaN(start.getTime()) || isNaN(end.getTime())) return '';

  const totalMonths = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth());
  const years = Math.floor(totalMonths / 12);
  const months = totalMonths % 12;

  let durationParts: string[] = [];
  if (years > 0) durationParts.push(`${years} year${years > 1 ? 's' : ''}`);
  if (showMonths && months > 0) durationParts.push(`${months} month${months > 1 ? 's' : ''}`);

  return durationParts.join(', ') || 'Less than a month';
};