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

export function formatDate(dateString: string | null | undefined): string {
	if (!dateString) return '';
	try {
		return format(parseISO(dateString), 'M/d/yyyy');
	} catch {
		return dateString;
	}
}

export function formatDateTime(dateString: string | null | undefined): string {
	if (!dateString) return '';
	try {
		const date = parseISO(dateString);
		return format(date, "M/d/yyyy 'at' h:mm a");
	} catch {
		return dateString;
	}
}

/**
 * Get the current month in YYYY-MM format
 */
export function getCurrentMonth(): string {
	const now = new Date();
	const year = now.getFullYear();
	const month = (now.getMonth() + 1).toString().padStart(2, '0');
	return `${year}-${month}`;
}

/**
 * Parse a YYYY-MM string into start and end dates for that month
 */
export function getMonthDateRange(month: string): { start: string; end: string } {
	const [year, monthNum] = month.split('-').map(Number);

	// First day of month
	const start = `${year}-${monthNum.toString().padStart(2, '0')}-01`;

	// Last day of month (day 0 of next month = last day of current month)
	const lastDay = new Date(year, monthNum, 0).getDate();
	const end = `${year}-${monthNum.toString().padStart(2, '0')}-${lastDay.toString().padStart(2, '0')}`;

	return { start, end };
}

/**
 * Get the current week's date range (Monday to Sunday) in YYYY-MM-DD format
 */
export function getWeekDateRange(): { start: string; end: string } {
	const now = new Date();
	const day = now.getDay();
	const diff = day === 0 ? -6 : 1 - day; // Monday = start

	const monday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + diff);
	const sunday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 6);

	const formatYMD = (d: Date) => {
		const y = d.getFullYear();
		const m = (d.getMonth() + 1).toString().padStart(2, '0');
		const day = d.getDate().toString().padStart(2, '0');
		return `${y}-${m}-${day}`;
	};

	return { start: formatYMD(monday), end: formatYMD(sunday) };
}
