<script lang="ts">
	import * as Card from '$lib/components/ui/card';
	import * as Table from '$lib/components/ui/table';
	import { Button } from '$lib/components/ui/button';
	import { Folder, FileDown, RefreshCw } from 'lucide-svelte';
	import { m } from '$lib/i18n/messages';
	import {
		AuditFilesAPI,
		type AuditFileBreadcrumb,
		type AuditFileItem,
		type AuditFolderItem
	} from '$lib/api/dashboard/a76/audit_files';
	import { companyStore } from '$lib/stores/company.svelte';
	import { getLocale } from '$lib/paraglide/runtime';

	let loading = $state(false);
	let error = $state<string | null>(null);
	let currentPath = $state('');
	let displayPath = $state('');
	let breadcrumbs = $state<AuditFileBreadcrumb[]>([]);
	let folders = $state<AuditFolderItem[]>([]);
	let files = $state<AuditFileItem[]>([]);

	function activeCompanyId(): number | undefined {
		return companyStore.activeCompany?.id;
	}

	function noActiveCompanyMessage() {
		return getLocale() === 'es' ? 'Selecciona una compañía activa.' : 'Select an active company.';
	}

	async function loadPath(path = '') {
		const cid = activeCompanyId();
		if (!cid) {
			error = noActiveCompanyMessage();
			folders = [];
			files = [];
			breadcrumbs = [];
			currentPath = '';
			displayPath = '';
			return;
		}
		loading = true;
		error = null;
		try {
			const res = await AuditFilesAPI.list(cid, { path, max_keys: 200 });
			currentPath = res.current_path ?? '';
			displayPath = res.display_path ?? '';
			breadcrumbs = res.breadcrumbs ?? [];
			folders = res.folders ?? [];
			files = res.files ?? [];
		} catch (e: unknown) {
			error = e instanceof Error ? e.message : String(e);
		} finally {
			loading = false;
		}
	}

	function formatSize(bytes: number) {
		if (!bytes || bytes < 0) return '0 B';
		const units = ['B', 'KB', 'MB', 'GB', 'TB'];
		let value = bytes;
		let idx = 0;
		while (value >= 1024 && idx < units.length - 1) {
			value /= 1024;
			idx++;
		}
		return `${value.toFixed(value >= 10 || idx === 0 ? 0 : 1)} ${units[idx]}`;
	}

	function formatDate(value?: string | null) {
		if (!value) return '—';
		try {
			return new Date(value).toLocaleString();
		} catch {
			return value;
		}
	}

	async function downloadFile(path: string, filename: string) {
		const cid = activeCompanyId();
		if (!cid) return;
		try {
			const blob = await AuditFilesAPI.downloadBlob(cid, path);
			const url = URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = filename;
			document.body.appendChild(a);
			a.click();
			a.remove();
			URL.revokeObjectURL(url);
		} catch (e: unknown) {
			error = e instanceof Error ? e.message : String(e);
		}
	}

	$effect(() => {
		const cid = companyStore.activeCompany?.id;
		if (!cid) {
			loading = false;
			folders = [];
			files = [];
			breadcrumbs = [];
			currentPath = '';
			displayPath = '';
			return;
		}
		void loadPath('');
	});
</script>

<div class="flex min-h-0 flex-1 flex-col gap-4">
	<Card.Root class="flex min-h-0 flex-1 flex-col overflow-hidden">
		<Card.Header class="flex-none py-3">
			<div class="flex items-center justify-between">
				<div>
					<Card.Title>{m['sidebar.audit_logs_files_title']()}</Card.Title>
					<Card.Description class="text-xs">
						<div class="mt-1 flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
							{#each breadcrumbs as crumb, idx}
								{#if idx > 0}
									<span class="mx-0.5 text-[10px]">/</span>
								{/if}
								{#if idx === breadcrumbs.length - 1}
									<span class="max-w-[240px] truncate font-medium text-foreground sm:max-w-[320px]">
										{crumb.display_name}
									</span>
								{:else}
									<button
										type="button"
										class="max-w-[180px] truncate hover:text-foreground hover:underline underline-offset-2"
										onclick={() => void loadPath(crumb.path)}
										disabled={loading}
									>
										{crumb.display_name}
									</button>
								{/if}
							{/each}
							{#if breadcrumbs.length === 0}
								{m['sidebar.audit_logs_files_root']()}
							{/if}
						</div>
					</Card.Description>
				</div>
				<Button variant="outline" size="sm" class="h-9" onclick={() => void loadPath(currentPath)} disabled={loading}>
					<RefreshCw class="mr-2 h-4 w-4 {loading ? 'animate-spin' : ''}" />
					{m['sidebar.audit_logs_files_refresh']()}
				</Button>
			</div>
		</Card.Header>
		<Card.Content class="flex min-h-0 flex-1 flex-col p-0 px-6 pb-6">
			{#if error}
				<div class="flex-none m-2 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950/40 dark:text-red-300">
					{m['sidebar.audit_logs_files_error_prefix']()} {error}
				</div>
			{/if}
			<div class="relative min-h-0 flex-1 overflow-auto rounded-md border bg-card shadow-inner">
				<Table.Root class="min-w-full text-sm">
					<Table.Header class="sticky top-0 z-10 bg-background/95 shadow-sm backdrop-blur-sm">
						<Table.Row>
							<Table.Head class="min-w-[200px]">
								{m['sidebar.audit_logs_files_col_name']()}
							</Table.Head>
							<Table.Head class="w-[110px]">
								{m['sidebar.audit_logs_files_col_size']()}
							</Table.Head>
							<Table.Head class="w-[160px]">
								{m['sidebar.audit_logs_files_col_modified']()}
							</Table.Head>
							<Table.Head class="w-[120px] text-left">
								{m['sidebar.audit_logs_files_col_actions']()}
							</Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#if loading}
							<Table.Row>
								<Table.Cell colspan={4} class="py-8 text-left text-muted-foreground">
									{m['sidebar.audit_logs_files_loading']()}
								</Table.Cell>
							</Table.Row>
						{:else if folders.length === 0 && files.length === 0}
							<Table.Row>
								<Table.Cell colspan={4} class="py-8 text-left text-muted-foreground">
									{m['sidebar.audit_logs_files_empty']()}
								</Table.Cell>
							</Table.Row>
						{:else}
							{#each folders as folder}
								<Table.Row
									class="cursor-pointer transition-colors hover:bg-muted/50"
									onclick={() => void loadPath(folder.path)}
								>
									<Table.Cell class="max-w-[260px] font-medium">
										<span class="inline-flex items-center gap-2 truncate text-left">
											<Folder class="h-4 w-4 flex-shrink-0 text-amber-500" />
											<span class="truncate">{folder.display_name}</span>
										</span>
									</Table.Cell>
									<Table.Cell class="text-muted-foreground">—</Table.Cell>
									<Table.Cell class="text-muted-foreground">—</Table.Cell>
									<Table.Cell class="text-left text-muted-foreground">—</Table.Cell>
								</Table.Row>
							{/each}
							{#each files as file}
								<Table.Row class="transition-colors hover:bg-muted/50">
									<Table.Cell class="max-w-[260px] font-medium">
										<span class="truncate">{file.display_name}</span>
									</Table.Cell>
									<Table.Cell>{formatSize(file.size)}</Table.Cell>
									<Table.Cell>{formatDate(file.last_modified)}</Table.Cell>
									<Table.Cell class="text-left">
										<Button
											size="icon"
											variant="outline"
											class="h-8 w-8"
											onclick={() => void downloadFile(file.path, file.display_name)}
										>
											<FileDown class="h-4 w-4" />
										</Button>
									</Table.Cell>
								</Table.Row>
							{/each}
						{/if}
					</Table.Body>
				</Table.Root>
			</div>
		</Card.Content>
	</Card.Root>
</div>
