import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { Active, Over } from '@dnd-kit/core';
// import { ColumnDragData } from '@/app/dashboard/kanban/_components/board-column';
// import { TaskDragData } from '@/app/dashboard/kanban/_components/task-card';

// type DraggableData = ColumnDragData | TaskDragData;

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function hasDraggableData<T extends Active | Over>(
  entry: T | null | undefined
): entry is T & {
  //   data: DataRef<DraggableData>;
} {
  if (!entry) {
    return false;
  }

  const data = entry.data.current;

  if (data?.type === 'Column' || data?.type === 'Task') {
    return true;
  }

  return false;
}

export function formatBytes(
  bytes: number,
  opts: {
    decimals?: number;
    sizeType?: 'accurate' | 'normal';
  } = {}
) {
  const { decimals = 0, sizeType = 'normal' } = opts;

  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const accurateSizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB'];
  if (bytes === 0) return '0 Byte';
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(decimals)} ${sizeType === 'accurate' ? accurateSizes[i] ?? 'Bytest' : sizes[i] ?? 'Bytes'
    }`;
}

export const formatDateTime = (time: string) => {
  // Format the input time in the desired string format, assuming it's in IST (local time)
  return `2024-01-01T${time}:00.000`;
};

export const toUTC = (time: string) => {
  const dateTimeString = formatDateTime(time);
  const localTime = new Date(dateTimeString);

  // Correct for IST (UTC +5:30) by subtracting 5 hours 30 minutes
  // JavaScript's Date constructor works in the local timezone, so we need to adjust it manually
  const utcTime = new Date(localTime.getTime() - (5 * 60 + 30) * 60000);

  // Return the time in UTC format (ISO string)
  return utcTime.toISOString();
};

export const formatTimeToUTC = (time: string): string => {
  const dateTimeString = `2024-01-01T${time}:00.000`;
  const localDate = new Date(dateTimeString);
  return localDate.toISOString();
};

export const formatUTCToLocalTime = (utcDateTime: string): string => {
  const date = new Date(utcDateTime);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};


export const formatDateStringToUTC = (dateString: string, isEndOfDay: boolean = false): string => {
  if (!dateString) return '';
  const datePart = dateString.split('T')[0];
  return isEndOfDay ? `${datePart}T23:59:59.000Z` : `${datePart}T00:00:00.000Z`;
};

export const formatUTCToDateString = (utcDateTime: string): string => {
  const date = new Date(utcDateTime);
  const year = date.getUTCFullYear();
  const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');
  const day = date.getUTCDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};


export const convertToUTCMilliseconds = (dateString: string) => {
  return new Date(`${dateString}T00:00:00Z`).getTime();
};

export const formatCategoryLabel = (str: string) => {
  if (!str) return "";
  return str
    .replace(/_/g, " ")          // replace "_" → " "
    .replace(/\b\w/g, c => c.toUpperCase()); // Uppercase first letter
};

export const formatOrderStatus = (status: string | null | undefined): string => {
  if (!status) return 'N/A';
  if (status.toLowerCase() === 'delivered') return 'Completed';
  if (status.toLowerCase() === 'ongoing') return 'Ongoing';
  return status
    .replace(/_/g, ' ')
    .trim()
    .replace(/\b\w/g, (char) => char.toUpperCase());
};

export const currency = "$";

export const getEffectiveDiscountedPrice = (item: any): number | null => {
  if (!item) return null;
  const price = Number(item.price);
  if (isNaN(price) || price <= 0) return null;

  if (
    item.discounted_price !== null &&
    item.discounted_price !== undefined &&
    !isNaN(Number(item.discounted_price))
  ) {
    const discPrice = Number(item.discounted_price);
    if (discPrice > 0 && discPrice < price) {
      return discPrice;
    }
  }

  const isDiscountActive =
    item.is_discount_active === true || item.is_discount_active === 'true';
  const discValue = Number(item.discount_value);

  if (isDiscountActive && !isNaN(discValue) && discValue > 0) {
    const discType = String(item.discount_type || 'percentage').toLowerCase();
    let calcPrice = price;
    if (discType === 'percentage' || discType === 'percent' || discType === '%') {
      const validPercent = Math.min(100, Math.max(0, discValue));
      calcPrice = Math.max(0, price - (price * (validPercent / 100)));
    } else {
      calcPrice = Math.max(0, price - discValue);
    }
    if (calcPrice < price) {
      return Number(calcPrice.toFixed(2));
    }
  }

  return null;
};