<script lang="ts">
	import { CalendarClock, Plus, Pencil, Trash2, Check } from '@lucide/svelte';
	import * as Card from '$lib/components/ui/card';
	import * as Table from '$lib/components/ui/table';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { activitiesAPI, type Activity, type ActivityInput } from '$lib/api/crm';
	import { ACTIVITY_TYPES, ACTIVITY_STATUS, labelOf, formatDate } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	let items = $state<Activity[]>([]);
	let loading = $state(false);
	let statusFilter = $state('');
	let modalOpen = $state(false);
	let saving = $state(false);
	let editingId = $state<number | null>(null);
	let form = $state<ActivityInput>({ activity_type: 'task', subject: '', status: 'pending' });

	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	$effect(() => {
		const cid = companyId;
		if (!cid) return;
		void load(cid);
	});

	async function load(cid: number) {
		loading = true;
		try {
			items = await activitiesAPI.list(cid, statusFilter ? { status: statusFilter } : undefined);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar las actividades');
		} finally {
			loading = false;
		}
	}

	function openCreate() {
		editingId = null;
		form = { activity_type: 'task', subject: '', status: 'pending' };
		modalOpen = true;
	}

	function openEdit(a: Activity) {
		editingId = a.id;
		form = { ...a };
		modalOpen = true;
	}

	async function save(event: SubmitEvent) {
		event.preventDefault();
		if (!companyId) return;
		if (!form.subject?.trim()) {
			toast.error('El asunto es obligatorio');
			return;
		}
		saving = true;
		try {
			const payload = { ...form, due_date: form.due_date || null };
			if (editingId) {
				await activitiesAPI.update(editingId, payload, companyId);
				toast.success('Actividad actualizada');
			} else {
				await activitiesAPI.create(payload, companyId);
				toast.success('Actividad creada');
			}
			modalOpen = false;
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo guardar la actividad');
		} finally {
			saving = false;
		}
	}

	async function complete(a: Activity) {
		if (!companyId) return;
		try {
			await activitiesAPI.complete(a.id, companyId);
			toast.success('Actividad completada');
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo completar la actividad');
		}
	}

	async function remove(a: Activity) {
		if (!companyId) return;
		if (!confirm(`¿Eliminar la actividad "${a.subject}"?`)) return;
		try {
			await activitiesAPI.remove(a.id, companyId);
			toast.success('Actividad eliminada');
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo eliminar la actividad');
		}
	}

	const statusClass: Record<string, string> = {
		pending: 'bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-400',
		completed: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400',
		canceled: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400'
	};
</script>

<div class="space-y-6">
	<div class="flex flex-wrap items-center justify-between gap-3">
		<div>
			<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
				<CalendarClock class="h-6 w-6" />
				Actividades
			</h1>
			<p class="mt-1 text-sm text-muted-foreground">Llamadas, reuniones, tareas y notas.</p>
		</div>
		<Button onclick={openCreate} disabled={!companyId}>
			<Plus class="mr-1 h-4 w-4" /> Nueva actividad
		</Button>
	</div>

	<Card.Root>
		<Card.Header>
			<select
				class="max-w-xs rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
				bind:value={statusFilter}
				onchange={() => companyId && load(companyId)}
			>
				<option value="">Todos los estados</option>
				{#each ACTIVITY_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}
			</select>
		</Card.Header>
		<Card.Content>
			{#if loading}
				<p class="py-6 text-center text-sm text-muted-foreground">Cargando…</p>
			{:else if items.length === 0}
				<p class="py-6 text-center text-sm text-muted-foreground">Sin actividades registradas.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Asunto</Table.Head>
								<Table.Head>Tipo</Table.Head>
								<Table.Head>Estado</Table.Head>
								<Table.Head>Vence</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each items as a (a.id)}
								<Table.Row>
									<Table.Cell class="font-medium">{a.subject}</Table.Cell>
									<Table.Cell>{labelOf(ACTIVITY_TYPES, a.activity_type)}</Table.Cell>
									<Table.Cell>
										<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {statusClass[a.status] ?? ''}">
											{labelOf(ACTIVITY_STATUS, a.status)}
										</span>
									</Table.Cell>
									<Table.Cell>{formatDate(a.due_date)}</Table.Cell>
									<Table.Cell class="text-right">
										{#if a.status === 'pending'}
											<Button variant="ghost" size="sm" onclick={() => complete(a)} aria-label="Completar" title="Marcar como completada">
												<Check class="h-4 w-4 text-emerald-600" />
											</Button>
										{/if}
										<Button variant="ghost" size="sm" onclick={() => openEdit(a)} aria-label="Editar">
											<Pencil class="h-4 w-4" />
										</Button>
										<Button variant="ghost" size="sm" onclick={() => remove(a)} aria-label="Eliminar">
											<Trash2 class="h-4 w-4 text-destructive" />
										</Button>
									</Table.Cell>
								</Table.Row>
							{/each}
						</Table.Body>
					</Table.Root>
				</div>
			{/if}
		</Card.Content>
	</Card.Root>
</div>

{#if modalOpen}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" role="presentation" onclick={() => (modalOpen = false)}>
		<div class="max-h-[90vh] w-full max-w-xl overflow-y-auto rounded-lg border bg-card p-6 shadow-lg" role="dialog" aria-modal="true" onclick={(e) => e.stopPropagation()}>
			<h2 class="mb-4 text-lg font-semibold">{editingId ? 'Editar actividad' : 'Nueva actividad'}</h2>
			<form class="grid gap-4 sm:grid-cols-2" onsubmit={save}>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2">
					<span class="font-medium">Asunto *</span>
					<input class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.subject} required />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Tipo</span>
					<select class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.activity_type}>
						{#each ACTIVITY_TYPES as t (t.value)}<option value={t.value}>{t.label}</option>{/each}
					</select>
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Estado</span>
					<select class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.status}>
						{#each ACTIVITY_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}
					</select>
				</label>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2">
					<span class="font-medium">Fecha límite</span>
					<input type="datetime-local" class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.due_date} />
				</label>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2">
					<span class="font-medium">Descripción</span>
					<textarea rows="3" class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.description}></textarea>
				</label>
				<div class="flex justify-end gap-2 sm:col-span-2">
					<Button type="button" variant="outline" onclick={() => (modalOpen = false)}>Cancelar</Button>
					<Button type="submit" disabled={saving}>{saving ? 'Guardando…' : 'Guardar'}</Button>
				</div>
			</form>
		</div>
	</div>
{/if}
