// Session component shared types
import type {
	ServiceSession$result,
	ProjectSession$result,
	Scope$result,
	ProjectScope$result
} from '$houdini';

// Session type discriminator
export type SessionType = 'service' | 'project';

// Tab type
export type SessionTab = 'summary' | 'tasks' | 'media' | 'notes';

// Service session types
export type ServiceSession = NonNullable<ServiceSession$result['serviceSession']>;
export type ServiceSessionPhoto = ServiceSession['photos'][number];
export type ServiceSessionVideo = ServiceSession['videos'][number];
export type ServiceSessionNote = ServiceSession['notes'][number];
export type ServiceSessionCompletedTask = ServiceSession['completedTasks'][number];

// Project session types
export type ProjectSession = NonNullable<ProjectSession$result['projectSession']>;
export type ProjectSessionPhoto = ProjectSession['photos'][number];
export type ProjectSessionVideo = ProjectSession['videos'][number];
export type ProjectSessionNote = ProjectSession['notes'][number];
export type ProjectSessionCompletedTask = ProjectSession['completedTasks'][number];

// Union types for components that handle both
export type SessionPhoto = ServiceSessionPhoto | ProjectSessionPhoto;
export type SessionVideo = ServiceSessionVideo | ProjectSessionVideo;
export type SessionNote = ServiceSessionNote | ProjectSessionNote;
export type SessionCompletedTask = ServiceSessionCompletedTask | ProjectSessionCompletedTask;

// Scope types
export type ServiceScope = NonNullable<Scope$result['scope']>;
export type ServiceArea = ServiceScope['areas'][number];
export type ServiceTask = ServiceArea['tasks'][number];

export type ProjectScope = NonNullable<ProjectScope$result['projectScope']>;
export type ProjectArea = ProjectScope['projectAreas'][number];
export type ProjectTask = ProjectArea['projectTasks'][number];

// Extended task type with additional fields for both types
export type ExtendedServiceTask = ServiceTask & {
	uuid: string;
	areaId: string;
	areaName: string;
};

export type ExtendedProjectTask = ProjectTask & {
	uuid: string;
	areaId: string;
	areaName: string;
};

export type ExtendedTask = ExtendedServiceTask | ExtendedProjectTask;

// Area with completions (for completed tasks section)
export interface ServiceAreaWithCompletions {
	area: ServiceArea;
	completions: ServiceSessionCompletedTask[];
}

export interface ProjectAreaWithCompletions {
	area: ProjectArea;
	completions: ProjectSessionCompletedTask[];
}

export type AreaWithCompletions = ServiceAreaWithCompletions | ProjectAreaWithCompletions;

// Area with tasks (for ready to submit section)
export interface ServiceAreaWithTasks {
	area: ServiceArea;
	tasks: ExtendedServiceTask[];
}

export interface ProjectAreaWithTasks {
	area: ProjectArea;
	tasks: ExtendedProjectTask[];
}

export type AreaWithTasks = ServiceAreaWithTasks | ProjectAreaWithTasks;

// Props interfaces for components
export interface SessionTabsCounts {
	tasks: number;
	photos: number;
	videos: number;
	notes: number;
}

// Helper function to format error messages
export function getErrorMessage(errors: { message: string }[] | null | undefined): string {
	return errors?.map((e) => e.message).join(', ') ?? '';
}

// Frequency badge colors - matches TaskFrequencyChoices enum from backend (lowercase)
export const frequencyColors: Record<string, string> = {
	daily: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
	weekly: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
	monthly: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
	quarterly: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
	triannual: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400',
	annual: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
	as_needed: 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400'
};

// Format frequency for display
export function formatFrequency(frequency: string | null | undefined): string {
	if (!frequency) return '';
	return frequency.replace('_', ' ').toLowerCase();
}

// Format date/time
export function formatDateTime(dateStr: string | null | undefined): string {
	if (!dateStr) return '';
	const date = new Date(dateStr);
	return date.toLocaleString('en-US', {
		month: 'short',
		day: 'numeric',
		year: 'numeric',
		hour: 'numeric',
		minute: '2-digit'
	});
}

export function formatDate(dateStr: string | null | undefined): string {
	if (!dateStr) return '';
	const date = new Date(dateStr);
	return date.toLocaleDateString('en-US', {
		month: 'short',
		day: 'numeric',
		year: 'numeric'
	});
}

export function formatTime(dateStr: string | null | undefined): string {
	if (!dateStr) return '';
	const date = new Date(dateStr);
	return date.toLocaleTimeString('en-US', {
		hour: 'numeric',
		minute: '2-digit'
	});
}

// Format duration
export function formatDuration(seconds: number | null | undefined): string {
	if (!seconds) return '0m';
	const hours = Math.floor(seconds / 3600);
	const minutes = Math.floor((seconds % 3600) / 60);
	if (hours > 0) {
		return `${hours}h ${minutes}m`;
	}
	return `${minutes}m`;
}

// API base URL for authenticated media requests
export const API_BASE_URL = 'https://api.example.com';

// Helper to get authenticated image URL by fetching the image and creating an object URL
export async function getAuthenticatedImageUrl(url: string): Promise<string> {
	try {
		// Add /v1 prefix for Oathkeeper routing if URL starts with /api/
		const apiPath = url.startsWith('/api/') ? `/v1${url}` : url;
		const fullUrl = `${API_BASE_URL}${apiPath}`;
		const response = await fetch(fullUrl, {
			credentials: 'include'
		});
		const blob = await response.blob();
		return URL.createObjectURL(blob);
	} catch (err) {
		console.error('Failed to fetch authenticated image:', err);
		return url; // Fallback to original URL
	}
}
