<script lang="ts">
	import { onMount } from 'svelte';
	import PageHeader from '$lib/components/layout/PageHeader.svelte';
	import LoadingState from '$lib/components/common/LoadingState.svelte';
	import EmptyState from '$lib/components/common/EmptyState.svelte';
	import { Calendar, FileText, AlertCircle, Users, FolderKanban } from 'lucide-svelte';
	import { 
		reportService, 
		formatViewType,
		getStatusBadgeClass,
		type ReportResponse,
		type ViewType,
		type VarianceStatus
	} from '$lib/services/reportService';
	import { projectService, type Project } from '$lib/services/projectService';
	import { teamMemberService, type TeamMember } from '$lib/services/teamMemberService';

	import MultiSelectDropdown from '$lib/components/common/MultiSelectDropdown.svelte';

	// State
	let report = $state<ReportResponse | null>(null);
	let projects = $state<Project[]>([]);
	let teamMembers = $state<TeamMember[]>([]);
	let loading = $state(true);
	let error = $state<string | null>(null);
	
	// Filter state
	let startDate = $state('');
	let endDate = $state('');
	let selectedProjects = $state<string[]>([]);
	let selectedMembers = $state<string[]>([]);
	let viewMode = $state<'aggregate' | 'detailed'>('aggregate');
	
	// Initialize with current quarter
	onMount(async () => {
		const now = new Date();
		const quarter = Math.floor(now.getMonth() / 3);
		const year = now.getFullYear();
		
		startDate = `${year}-${String(quarter * 3 + 1).padStart(2, '0')}-01`;
		endDate = `${year}-${String((quarter + 1) * 3).padStart(2, '0')}-${new Date(year, (quarter + 1) * 3, 0).getDate()}`;
		
		await Promise.all([loadProjects(), loadTeamMembers(), loadReport()]);
	});

	async function loadProjects() {
		try {
			projects = await projectService.getAll();
		} catch (err) {
			console.error('Error loading projects:', err);
		}
	}

	async function loadTeamMembers() {
		try {
			teamMembers = await teamMemberService.getAll(true);
		} catch (err) {
			console.error('Error loading team members:', err);
		}
	}

	async function loadReport() {
		if (!startDate || !endDate) return;
		
		try {
			loading = true;
			error = null;
			const response = await reportService.getAllocations({
				start_date: startDate,
				end_date: endDate,
				project_ids: selectedProjects.length > 0 ? selectedProjects : undefined,
				member_ids: selectedMembers.length > 0 ? selectedMembers : undefined,
			});
			report = response;
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to load report';
			console.error('Error loading report:', err);
		} finally {
			loading = false;
		}
	}

	function handleApplyFilters() {
		loadReport();
	}

	function parseDateString(value: string): Date {
		const [year, month, day] = value.split('-').map(Number);
		return new Date(year, month - 1, day);
	}

	function formatDisplayDate(value: string): string {
		if (!value) return '';
		const date = parseDateString(value);
		return isNaN(date.getTime()) ? '' : date.toLocaleDateString();
	}

	function formatMonthLabel(value: string): string {
		if (!value) return '';
		const normalized = value.split('-').length === 3 ? value : `${value}-01`;
		const date = parseDateString(normalized);
		return isNaN(date.getTime())
			? ''
			: date.toLocaleDateString(undefined, { month: 'short', year: 'numeric' });
	}

	function formatHours(hours: number | null | undefined): string {
		const value = typeof hours === 'number' && isFinite(hours) ? hours : 0;
		return `${value.toFixed(1)}h`;
	}

	function getViewTypeBadgeClass(viewType: ViewType): string {
		switch (viewType) {
			case 'did':
				return 'bg-gray-100 text-gray-800';
			case 'is':
				return 'bg-blue-100 text-blue-800';
			case 'will':
				return 'bg-purple-100 text-purple-800';
		}
	}
</script>

<svelte:head>
	<title>Allocation Report | Headroom</title>
</svelte:head>

<PageHeader 
	title="Allocation Report" 
	description="Resource planning and execution analysis across projects and team members"
/>

<!-- Filters -->
<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-5 mb-6">
	<div class="grid grid-cols-[auto_auto_1fr_auto_auto] gap-x-4 gap-y-3 items-end max-lg:grid-cols-2 max-lg:gap-3 max-sm:grid-cols-1">
		<!-- Start Date -->
		<div class="flex flex-col gap-1.5">
			<label class="text-xs font-semibold text-gray-500 uppercase tracking-wide">Start Date</label>
			<input
				type="date"
				bind:value={startDate}
				class="w-full rounded-md border border-gray-300 bg-white px-3 py-[0.4375rem] text-sm text-gray-900 shadow-sm transition hover:border-indigo-400 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 focus:outline-none"
			/>
		</div>

		<!-- End Date -->
		<div class="flex flex-col gap-1.5">
			<label class="text-xs font-semibold text-gray-500 uppercase tracking-wide">End Date</label>
			<input
				type="date"
				bind:value={endDate}
				class="w-full rounded-md border border-gray-300 bg-white px-3 py-[0.4375rem] text-sm text-gray-900 shadow-sm transition hover:border-indigo-400 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 focus:outline-none"
			/>
		</div>

		<!-- Projects multi-select — fills remaining space -->
		<div class="min-w-0 max-lg:col-span-2 max-sm:col-span-1">
			<MultiSelectDropdown
				label="Projects"
				placeholder="All projects"
				options={projects.map((project) => ({ id: project.id, label: `${project.code} - ${project.title}` }))}
				bind:selected={selectedProjects}
			/>
		</div>

		<!-- View Mode -->
		<div class="flex flex-col gap-1.5">
			<label class="text-xs font-semibold text-gray-500 uppercase tracking-wide">View Mode</label>
			<select
				bind:value={viewMode}
				class="w-full rounded-md border border-gray-300 bg-white px-3 py-[0.4375rem] text-sm text-gray-900 shadow-sm transition hover:border-indigo-400 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 focus:outline-none"
			>
				<option value="aggregate">Aggregate</option>
				<option value="detailed">Detailed</option>
			</select>
		</div>

		<!-- Apply -->
		<div class="flex items-end">
			<button
				type="button"
				on:click={handleApplyFilters}
				disabled={loading || !startDate || !endDate}
				class="inline-flex items-center justify-center px-5 py-[0.4375rem] rounded-md text-sm font-medium text-white bg-indigo-600 shadow-sm transition hover:bg-indigo-700 active:bg-indigo-800 disabled:bg-gray-300 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-indigo-500/20 whitespace-nowrap"
			>
				{#if loading}
					<span class="animate-spin mr-2">⟳</span> Loading…
				{:else}
					Apply Filters
				{/if}
			</button>
		</div>
	</div>
</div>

<!-- Error State -->
{#if error}
	<div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
		<div class="flex items-center">
			<AlertCircle class="h-5 w-5 text-red-400 mr-2" />
			<p class="text-red-800">{error}</p>
		</div>
	</div>
{/if}

<!-- Loading State -->
{#if loading}
	<LoadingState type="text" />
{/if}

<!-- Report Content -->
{#if report && !loading}
	<!-- View Type Badge -->
	<div class="mb-6 flex items-center gap-4">
		<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium {getViewTypeBadgeClass(report.view_type)}">
			<Calendar class="h-4 w-4 mr-1" />
			{formatViewType(report.view_type)}
		</span>
		<span class="text-sm text-gray-500">
			Period: {formatDisplayDate(report.period.start)} - {formatDisplayDate(report.period.end)}
		</span>
	</div>

	<!-- Aggregates Summary -->
	<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
		<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
			<p class="text-sm text-gray-500 mb-1">Total Planned</p>
			<p class="text-2xl font-bold text-gray-900">{formatHours(report.aggregates.total_planned)}</p>
		</div>
		<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
			<p class="text-sm text-gray-500 mb-1">Total Allocated</p>
			<p class="text-2xl font-bold text-gray-900">{formatHours(report.aggregates.total_allocated)}</p>
		</div>
		<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
			<p class="text-sm text-gray-500 mb-1">Variance</p>
			<p class="text-2xl font-bold {report.aggregates.total_variance > 0 ? 'text-red-600' : report.aggregates.total_variance < 0 ? 'text-amber-600' : 'text-green-600'}">
				{report.aggregates.total_variance > 0 ? '+' : ''}{formatHours(report.aggregates.total_variance)}
			</p>
		</div>
		<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
			<p class="text-sm text-gray-500 mb-1">Status</p>
			<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium {getStatusBadgeClass(report.aggregates.status)}">
				{report.aggregates.status}
			</span>
		</div>
	</div>

	{#if viewMode === 'aggregate'}
		<!-- Aggregate View: Project Summary Table -->
		<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mb-6">
			<div class="px-4 py-3 border-b border-gray-200 flex items-center">
				<FolderKanban class="h-5 w-5 text-gray-400 mr-2" />
				<h3 class="text-lg font-medium text-gray-900">Project Summary</h3>
			</div>
			<table class="min-w-full divide-y divide-gray-200">
				<thead class="bg-gray-50">
					<tr>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Project</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Approved Estimate</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Plan Sum</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Period Planned</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Period Allocated</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Variance</th>
						<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Status</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-gray-200">
					{#each report.projects as project}
						<tr class="hover:bg-gray-50">
							<td class="px-4 py-3">
								<div class="font-medium text-gray-900">{project.code}</div>
								<div class="text-sm text-gray-500">{project.title}</div>
							</td>
							<td class="px-4 py-3 text-right text-sm text-gray-900">{formatHours(project.approved_estimate)}</td>
							<td class="px-4 py-3 text-right text-sm text-gray-900">{formatHours(project.plan_sum)}</td>
							<td class="px-4 py-3 text-right text-sm text-gray-900">{formatHours(project.period_planned)}</td>
							<td class="px-4 py-3 text-right text-sm text-gray-900">{formatHours(project.period_allocated)}</td>
							<td class="px-4 py-3 text-right text-sm {project.period_variance > 0 ? 'text-red-600' : project.period_variance < 0 ? 'text-amber-600' : 'text-green-600'}">
								{project.period_variance > 0 ? '+' : ''}{formatHours(project.period_variance)}
							</td>
							<td class="px-4 py-3 text-center">
								<span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium {getStatusBadgeClass(project.period_status)}">
									{project.period_status}
								</span>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>

		<!-- Member Summary Table -->
		<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
			<div class="px-4 py-3 border-b border-gray-200 flex items-center">
				<Users class="h-5 w-5 text-gray-400 mr-2" />
				<h3 class="text-lg font-medium text-gray-900">Member Summary</h3>
			</div>
			<table class="min-w-full divide-y divide-gray-200">
				<thead class="bg-gray-50">
					<tr>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Member</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Period Allocated</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Project Breakdown</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-gray-200">
					{#each report.members as member}
						<tr class="hover:bg-gray-50">
							<td class="px-4 py-3 text-sm font-medium text-gray-900">{member.name}</td>
							<td class="px-4 py-3 text-right text-sm text-gray-900">{formatHours(member.period_allocated)}</td>
							<td class="px-4 py-3 text-sm">
								<div class="flex flex-wrap gap-2">
									{#each member.projects as proj}
										<span class="inline-flex items-center px-2 py-1 rounded text-xs bg-gray-100">
											{proj.project_code}: {formatHours(proj.total_hours)}
										</span>
										{/each}
								</div>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
	{:else}
		<!-- Detailed View: Project-Month Breakdown -->
		{#each report.projects as project}
			<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mb-4">
				<div class="px-4 py-3 border-b border-gray-200 bg-gray-50 flex items-center justify-between">
					<div>
						<span class="font-medium text-gray-900">{project.code}</span>
						<span class="text-gray-500 mx-2">-</span>
						<span class="text-gray-700">{project.title}</span>
					</div>
					<div class="flex items-center gap-4 text-sm">
						<span class="text-gray-500">Lifecycle: <span class="font-medium {project.lifecycle_status === 'OVER' ? 'text-red-600' : project.lifecycle_status === 'UNDER' ? 'text-amber-600' : 'text-green-600'}">{project.lifecycle_status}</span></span>
					</div>
				</div>
				<table class="min-w-full divide-y divide-gray-200">
					<thead class="bg-gray-50">
						<tr>
							<th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Month</th>
							<th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Planned</th>
							<th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Allocated</th>
							<th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Variance</th>
							<th class="px-4 py-2 text-center text-xs font-medium text-gray-500 uppercase">Status</th>
						</tr>
					</thead>
					<tbody class="divide-y divide-gray-200">
						{#each project.months as month}
							<tr class="hover:bg-gray-50">
								<td class="px-4 py-2 text-sm text-gray-900">{formatMonthLabel(month.month)}</td>
								<td class="px-4 py-2 text-right text-sm">
									{#if month.is_blank}
										<span class="text-gray-400 italic">blank</span>
									{:else}
										{formatHours(month.planned_hours ?? 0)}
									{/if}
								</td>
								<td class="px-4 py-2 text-right text-sm text-gray-900">{formatHours(month.allocated_hours)}</td>
								<td class="px-4 py-2 text-right text-sm {month.variance > 0 ? 'text-red-600' : month.variance < 0 ? 'text-amber-600' : 'text-green-600'}">
									{month.variance > 0 ? '+' : ''}{formatHours(month.variance)}
								</td>
								<td class="px-4 py-2 text-center">
									<span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium {getStatusBadgeClass(month.status)}">
										{month.status}
									</span>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/each}
	{/if}
{:else if !loading}
	<EmptyState 
		title="No Data"
		description="Select a date range and apply filters to generate a report."
		icon={FileText}
	/>
{/if}
