import { format, differenceInYears, parseISO } from 'date-fns';

export const formatCurrency = (amount: number): string => {
  return `\u20b9${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

export const formatCurrencyShort = (amount: number): string => {
  if (amount >= 100000) return `\u20b9${(amount / 100000).toFixed(1)}L`;
  if (amount >= 1000) return `\u20b9${(amount / 1000).toFixed(1)}K`;
  return `\u20b9${amount}`;
};

export const formatDate = (date: string | Date): string => {
  if (!date) return '-';
  const d = typeof date === 'string' ? parseISO(date) : date;
  return format(d, 'dd MMM yyyy');
};

export const formatDateShort = (date: string | Date): string => {
  if (!date) return '-';
  const d = typeof date === 'string' ? parseISO(date) : date;
  return format(d, 'dd/MM/yyyy');
};

export const formatTime = (time: string): string => {
  return time;
};

export const calculateAge = (dateOfBirth: string): number => {
  if (!dateOfBirth) return 0;
  return differenceInYears(new Date(), parseISO(dateOfBirth));
};

export const formatNumber = (num: number): string => {
  return num.toLocaleString('en-IN');
};

export const formatPercentage = (value: number): string => {
  return `${value.toFixed(1)}%`;
};

export const getInitials = (name: string): string => {
  if (!name) return '?';
  const parts = name.split(' ').filter(Boolean);
  if (parts.length === 1) return parts[0].charAt(0).toUpperCase();
  return (parts[0].charAt(0) + parts[parts.length - 1].charAt(0)).toUpperCase();
};

export const generateStudentId = (lastId: number): string => {
  const next = lastId + 1;
  return `SK${String(next).padStart(3, '0')}`;
};

export const generatePassword = (name: string, phone: string): string => {
  const namePart = name.toLowerCase().replace(/\s/g, '').slice(0, 4);
  const phonePart = phone.slice(-4);
  return `${namePart}${phonePart}`;
};

export const getMonthName = (monthIndex: number): string => {
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return months[monthIndex] || '';
};

export const getDaysInMonth = (year: number, month: number): number => {
  return new Date(year, month + 1, 0).getDate();
};

export const getDayName = (dayIndex: number): string => {
  const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  return days[dayIndex] || '';
};
