import fetchUserData from "../custom-hooks/fetch-hook";

const getSpeciality = async (ids, type) => {
	const specialites = await fetchUserData(`ssas/v1/ssas_${type}`, '');
	const selectedSpeciality = [];

	specialites.forEach(speciality => {
		ids.forEach(id => {
			if (speciality.id == id) {
				selectedSpeciality.push(speciality.name);
			}
		})
	});

	return selectedSpeciality;
}

const convertIndTimeZone = (date) => {
	const istDate = new Date(date.toLocaleString("en-US", { timeZone: "Asia/Kolkata" }));

	// Format to YYYY-MM-DD
	const yyyy = istDate.getFullYear();
	const mm = String(istDate.getMonth() + 1).padStart(2, '0');
	const dd = String(istDate.getDate()).padStart(2, '0');

	const formattedDate = `${yyyy}-${mm}-${dd}`;

	return formattedDate;
}

const convertDate = (date) => {
	const readableDate = new Date(date).toLocaleString("en-IN", {
		weekday: "long",
		year: "numeric",
		month: "long",
		day: "numeric",
		hour: "2-digit",
		minute: "2-digit",
		hour12: true,
	});

	return readableDate;
}

function convertFormattedDate(selectedDate) {
	const readableDate = new Date(selectedDate).toLocaleString("en-IN", {
		weekday: "long",
		year: "numeric",
		month: "long",
		day: "numeric",
	});

	return readableDate;
}

function convertFormattedTime(selectedTime) {
	const readableDate = new Date(selectedTime).toLocaleString("en-IN", {
		hour: "2-digit",
		minute: "2-digit",
		hour12: true,
	});

	return readableDate;
}

function getFormattedDate(selectedDate, selectedTime) {
	let date = selectedDate;

	// If selectedDate is a string (e.g., "2025-07-02"), convert it
	if (typeof date === 'string') {
		date = new Date(date);
	}

	// Ensure it's a valid Date
	if (!(date instanceof Date) || isNaN(date.getTime())) {
		return
	}

	const [hours, minutes, seconds] = selectedTime.split(':').map(Number);

	const dateWithTime = new Date(
		date.getFullYear(),
		date.getMonth(),
		date.getDate(),
		hours,
		minutes,
		seconds
	);

	return convertDate(dateWithTime);
}

export { getSpeciality, convertDate, getFormattedDate, convertFormattedDate, convertFormattedTime, convertIndTimeZone };
