// Session component shared types
import type {
	ServiceSession,
	ProjectSession,
	SessionNote,
	SessionImage,
	SessionVideo,
	ServiceTaskCompletion,
	ProjectTaskCompletion,
	ServiceScopeTask,
	ProjectScopeTask
} from '$lib/graphql/queries/session';

// Re-export for convenience
export type {
	ServiceSession,
	ProjectSession,
	SessionNote,
	SessionImage,
	SessionVideo,
	ServiceTaskCompletion,
	ProjectTaskCompletion,
	ServiceScopeTask,
	ProjectScopeTask
};

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

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

// Union types for components that handle both
export type Session = ServiceSession | ProjectSession;
export type TaskCompletion = ServiceTaskCompletion | ProjectTaskCompletion;

// Extended task type with area context
export interface ExtendedServiceTask extends ServiceScopeTask {
	uuid: string;
	areaId: string;
	areaName: string;
}

export interface ExtendedProjectTask extends ProjectScopeTask {
	uuid: string;
	areaId: string;
	areaName: string;
}

export type ExtendedTask = ExtendedServiceTask | ExtendedProjectTask;

// Area types from scope
export interface ServiceArea {
	id: string;
	name: string;
	description: string | null;
	order: number;
	tasks: ServiceScopeTask[];
}

export interface ProjectArea {
	id: string;
	name: string;
	description: string | null;
	order: number;
	tasks: ProjectScopeTask[];
}

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

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

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;
}

// Re-export frequency types for convenience
export type { TaskFrequency } from '$lib/graphql/queries/service-scope-templates';

// 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
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
// Use production API even in dev so cookies work (same domain as auth)
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(path: string): Promise<string> {
	try {
		// Normalize the path to include /api/media/ prefix
		let mediaPath = path;
		if (!path.startsWith('/')) {
			// Relative path from database (e.g., "uploads/project_session/...")
			mediaPath = `/api/media/${path}`;
		} else if (!path.startsWith('/api/')) {
			// Absolute path without /api prefix
			mediaPath = `/api/media${path}`;
		}
		// Add /v2 prefix for Oathkeeper routing (Rust backend)
		const fullUrl = `${API_BASE_URL}/v2${mediaPath}`;
		const response = await fetch(fullUrl, {
			credentials: 'include'
		});
		if (!response.ok) {
			throw new Error(`HTTP ${response.status}`);
		}
		const blob = await response.blob();
		return URL.createObjectURL(blob);
	} catch (err) {
		console.error('Failed to fetch authenticated image:', path, err);
		// Return a placeholder instead of the raw path to avoid broken relative URLs
		return '/placeholder-image.svg';
	}
}

// Helper to revoke object URLs when done
export function revokeAuthenticatedUrl(url: string): void {
	if (url.startsWith('blob:')) {
		URL.revokeObjectURL(url);
	}
}

// Type guard for service session
export function isServiceSession(session: Session): session is ServiceSession {
	return 'serviceId' in session;
}

// Type guard for project session
export function isProjectSession(session: Session): session is ProjectSession {
	return 'projectId' in session;
}

// Type guard for service task (has frequency)
export function isServiceTask(task: ExtendedTask): task is ExtendedServiceTask {
	return 'frequency' in task;
}

// Get session color classes based on type
export function getSessionColorClasses(type: SessionType): {
	primary: string;
	bg: string;
	border: string;
	borderLight: string;
	ring: string;
} {
	if (type === 'service') {
		return {
			primary: 'text-secondary-600 dark:text-secondary-400',
			bg: 'bg-secondary-500',
			border: 'border-secondary-500',
			borderLight: 'border-secondary-200 dark:border-secondary-700',
			ring: 'ring-secondary-500'
		};
	}
	return {
		primary: 'text-accent-600 dark:text-accent-400',
		bg: 'bg-accent-500',
		border: 'border-accent-500',
		borderLight: 'border-accent-200 dark:border-accent-700',
		ring: 'ring-accent-500'
	};
}
