<script setup lang="ts">
import type { SetupContext } from 'vue'
import type { CalendarEvent } from '../CalendarTypes'
import { formatDate } from '@bagelink/vue'
import { computed, useSlots } from 'vue'

interface MonthViewEvent {
	date: Date
	events: CalendarEvent[]
	isToday: boolean
	isCurrentMonth: boolean
}

const props = defineProps<{
	events: CalendarEvent[]
	startDate: Date
}>()

const emit = defineEmits<{
	(e: 'eventClick', event: CalendarEvent): void
	(e: 'openPopover', event: CalendarEvent, position?: { top: number, left: number }): void
}>()

const slots: SetupContext['slots'] = useSlots()

// Responsive state
const isMobile = computed(() => window.innerWidth < 768)

// Calendar data
const weekDays = computed(() => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])

// Calculate days for the current month view
const currentMonth = computed(() => {
	const year = props.startDate.getFullYear()
	const month = props.startDate.getMonth()
	const firstDay = new Date(year, month, 1)
	const lastDay = new Date(year, month + 1, 0)
	const daysInMonth = lastDay.getDate()
	const startingDay = firstDay.getDay() // 0 = Sunday, 1 = Monday, etc.
	const today = new Date().toDateString()
	const days: MonthViewEvent[] = []

	// Add days from previous month to fill the calendar grid
	const prevMonthLastDay = new Date(year, month, 0).getDate()
	for (let i = startingDay - 1; i >= 0; i--) {
		const date = new Date(year, month - 1, prevMonthLastDay - i)
		days.push({
			date,
			events: [],
			isToday: false,
			isCurrentMonth: false
		})
	}

	// Add days from current month
	for (let i = 1; i <= daysInMonth; i++) {
		const date = new Date(year, month, i)
		const dayEvents = props.events.filter((event) => {
			const eventDate = new Date(event.start_time)
			return eventDate.getDate() === i
				&& eventDate.getMonth() === month
				&& eventDate.getFullYear() === year
		})

		days.push({
			date,
			events: dayEvents,
			isToday: date.toDateString() === today,
			isCurrentMonth: true
		})
	}

	// Add days from next month to complete the grid
	const remainingDays = 42 - days.length // 42 = 6 rows * 7 days
	for (let i = 1; i <= remainingDays; i++) {
		const date = new Date(year, month + 1, i)
		days.push({
			date,
			events: [],
			isToday: false,
			isCurrentMonth: false
		})
	}

	return days
})

// Update event handling to emit the openPopover event
function handleEventSelection(event: CalendarEvent, domEvent?: MouseEvent) {
	if (!slots.eventContent) {
		emit('eventClick', event)
		return
	}

	// Calculate position from DOM event if available
	if (domEvent) {
		const rect = (domEvent.currentTarget as HTMLElement).getBoundingClientRect()
		const position = {
			top: rect.top + window.scrollY + (rect.height / 2),
			left: rect.left + window.scrollX + rect.width + 10
		}
		emit('openPopover', event, position)
	} else {
		emit('openPopover', event)
	}
}
</script>

<template>
	<div class="month-view">
		<div class="month-header">
			<div v-for="day in weekDays" :key="day" class="weekday">
				{{ day }}
			</div>
		</div>
		<div class="month-grid">
			<div
				v-for="day in currentMonth" :key="day.date.toISOString()" class="day-cell" :class="{
					'current-month': day.isCurrentMonth,
					'today': day.isToday,
					'other-month': !day.isCurrentMonth,
				}"
			>
				<div class="day-number">
					{{ formatDate(day.date, { format: 'DD' }) }}
				</div>
				<div class="day-events">
					<template v-if="isMobile">
						<div v-if="day.events.length > 0" class="event-dot" />
					</template>
					<template v-else>
						<div
							v-for="event in day.events" :key="event.id" class="event-item"
							:style="{ backgroundColor: event.color || 'var(--bgl-primary)' }"
							@click.stop="handleEventSelection(event, $event)"
						>
							<div class="event-title">
								{{ event.title }}
							</div>
							<div class="event-time">
								{{ formatDate(event.start_time, 'HH:mm') }}
							</div>
						</div>
					</template>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
.month-view {
	display: flex;
	flex-direction: column;
	height: 100%;
	overflow: hidden;
}

.month-header {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	border-bottom: 1px solid var(--border-color);
}

.weekday {
	padding: 0.5rem;
	text-align: center;
	color: var(--text-muted);
}

.month-grid {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	grid-template-rows: repeat(6, 1fr);
	flex-grow: 1;
	overflow: auto;
	border-inline-end: 1px solid var(--border-color);

}

.day-cell {
	border-inline-start: 1px solid var(--border-color);
	border-bottom: 1px solid var(--border-color);
	padding: 0.5rem;
	min-height: 100px;
	display: flex;
	flex-direction: column;
}

.day-number {
	margin-bottom: 0.5rem;
}

.other-month {
	background-color: var(--bgl-gray-light);
	color: var(--bgl-gray);
}

.today {
	background-color: var(--bgl-primary-light);
}

.today .day-number {
	color: var(--bgl-primary);
}

.day-events {
	flex-grow: 1;
	overflow-y: auto;
}

.event-item {
	margin-bottom: 0.25rem;
	padding: 0.25rem;
	border-radius: 4px;
	color: white;
	font-size: 0.8rem;
	cursor: pointer;
	transition: all 0.2s ease;
	display: flex;
		align-items: center;
		gap: 0.25rem;
		min-width: 0;
		justify-content: space-between;
		/* Allow flex items to shrink */
}

.event-title {
	font-weight: 500;
	/* white-space: nowrap; */
		height: 1lh;
	overflow: hidden;
	text-overflow: ellipsis;

}

.event-time {
	font-size: 0.7rem;
	opacity: 0.8;
}

.event-dot {
	width: 6px;
	height: 6px;
	background-color: var(--bgl-primary);
	border-radius: 50%;
	margin: 0.25rem auto;
}

.custom-popover {
	position: fixed;
	z-index: 1000;
	min-width: 250px;
	max-width: 350px;
	background-color: white;
	border-radius: var(--btn-border-radius);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
	animation: fadeIn 0.2s ease;
	transform-origin: center left;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: scale(0.95);
	}

	to {
		opacity: 1;
		transform: scale(1);
	}
}

@media (max-width: 768px) {
	.day-cell {
		min-height: 60px;
		padding: 0.25rem;
	}

	.day-number {
		font-size: 0.8rem;
		margin-bottom: 0.25rem;
	}

	.weekday {
		font-size: 0.8rem;
		padding: 0.25rem;
	}
}
</style>
