<script lang="ts">
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	interface ServiceDisplay {
		date: string;
		accountName: string;
		addressName: string | null;
		address: string | null;
	}

	type ColumnType = 'unassigned' | 'readyToAssign' | 'assigned';

	interface Props {
		service: ServiceDisplay;
		column: ColumnType;
		isUpdating: boolean;
		// For unassigned column
		teamMemberNames?: string[];
		isEditingDate?: boolean;
		// For readyToAssign column
		availableMembers?: { pk: string; name: string }[];
		stagedMembers?: { pk: string; name: string }[];
		hasStaged?: boolean;
		isDropdownOpen?: boolean;
		// For assigned column
		nonDispatchTeamMemberNames?: string[];
		// Selection
		isSelected?: boolean;
		showCheckbox?: boolean;
		// Callbacks
		onAddDispatch?: () => void;
		onRemoveDispatch?: () => void;
		onSubmitStaged?: () => void;
		onRemoveNonDispatch?: () => void;
		onStageTeamMember?: (memberPk: string) => void;
		onUnstageTeamMember?: (memberPk: string) => void;
		onToggleDropdown?: () => void;
		onToggleSelection?: () => void;
		// Unassigned column specific callbacks
		onUpdateDate?: (newDate: string) => void;
		onDelete?: () => void;
		onStartEditDate?: () => void;
		onCancelEditDate?: () => void;
	}

	let {
		service,
		column,
		isUpdating,
		teamMemberNames = [],
		isEditingDate = false,
		availableMembers = [],
		stagedMembers = [],
		hasStaged = false,
		isDropdownOpen = false,
		nonDispatchTeamMemberNames = [],
		isSelected = false,
		showCheckbox = false,
		onAddDispatch,
		onRemoveDispatch,
		onSubmitStaged,
		onRemoveNonDispatch,
		onStageTeamMember,
		onUnstageTeamMember,
		onToggleDropdown,
		onToggleSelection,
		onUpdateDate,
		onDelete,
		onStartEditDate,
		onCancelEditDate
	}: Props = $props();

	// Local state for date editing - initialized fresh when editing starts
	let editDateValue = $state('');

	// Reset edit value when editing starts
	$effect(() => {
		if (isEditingDate) {
			editDateValue = service.date;
		}
	});

	function formatServiceDate(dateString: string): string {
		const date = new Date(dateString + 'T00:00:00');
		return date.toLocaleDateString('en-US', {
			weekday: 'short',
			month: 'short',
			day: 'numeric'
		});
	}

	function handleDateSubmit() {
		if (editDateValue && editDateValue !== service.date) {
			onUpdateDate?.(editDateValue);
		} else {
			onCancelEditDate?.();
		}
	}

	function handleDateKeydown(e: KeyboardEvent) {
		if (e.key === 'Enter') {
			handleDateSubmit();
		} else if (e.key === 'Escape') {
			onCancelEditDate?.();
		}
	}

	function handleCheckboxClick(e: MouseEvent) {
		e.stopPropagation();
		onToggleSelection?.();
	}
</script>

<div
	class="group relative rounded-lg border bg-theme p-3 transition-all hover:shadow-md {isSelected
		? 'border-primary-500 ring-1 ring-primary-500'
		: 'border-theme hover:border-theme'}"
>
	{#if isUpdating}
		<div class="bg-theme/80 absolute inset-0 z-10 flex items-center justify-center rounded-lg">
			<IconSpinner class="h-6 w-6 text-secondary-500" />
		</div>
	{/if}

	<!-- Checkbox for bulk selection -->
	{#if showCheckbox}
		<button
			onclick={handleCheckboxClick}
			class="absolute top-2 right-2 z-10 flex h-5 w-5 items-center justify-center rounded border transition-colors {isSelected
				? 'border-primary-500 bg-primary-500 text-white'
				: 'border-gray-300 bg-white hover:border-primary-400 dark:border-gray-600 dark:bg-gray-800 dark:hover:border-primary-500'}"
			aria-label={isSelected ? 'Deselect service' : 'Select service'}
		>
			{#if isSelected}
				<svg class="h-3 w-3" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="3"
						d="M5 13l4 4L19 7"
					/>
				</svg>
			{/if}
		</button>
	{/if}

	<!-- Date display/edit for unassigned column -->
	{#if column === 'unassigned' && isEditingDate}
		<div class="mb-2 flex items-center gap-2">
			<input
				type="date"
				bind:value={editDateValue}
				onkeydown={handleDateKeydown}
				class="w-full rounded border border-theme bg-theme px-2 py-1 text-sm text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
			/>
			<button
				onclick={handleDateSubmit}
				class="rounded bg-green-500 p-1 text-white hover:bg-green-600"
				aria-label="Save date"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M5 13l4 4L19 7"
					/>
				</svg>
			</button>
			<button
				onclick={() => {
					editDateValue = service.date;
					onCancelEditDate?.();
				}}
				class="rounded bg-gray-500 p-1 text-white hover:bg-gray-600"
				aria-label="Cancel"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M6 18L18 6M6 6l12 12"
					/>
				</svg>
			</button>
		</div>
	{:else if column === 'unassigned'}
		<button
			onclick={onStartEditDate}
			class="mb-1 flex items-center gap-1 text-sm font-bold text-theme hover:text-primary-600 dark:hover:text-primary-400"
			title="Click to edit date"
		>
			{formatServiceDate(service.date)}
			<svg
				class="h-3 w-3 opacity-0 transition-opacity group-hover:opacity-100"
				style="fill: none"
				viewBox="0 0 24 24"
				stroke="currentColor"
			>
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					stroke-width="2"
					d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
				/>
			</svg>
		</button>
	{:else}
		<div class="mb-1 text-sm font-bold text-theme">{formatServiceDate(service.date)}</div>
	{/if}

	<div
		class="mb-1 text-sm font-semibold text-secondary-600 dark:text-secondary-400 {showCheckbox
			? 'pr-6'
			: ''}"
	>
		{service.accountName}
	</div>
	<div class="mb-2 text-xs text-theme-muted">{service.addressName ?? service.address}</div>

	{#if column === 'unassigned'}
		<!-- Unassigned column footer -->
		<div class="flex items-center justify-between border-t border-theme pt-2">
			<button
				onclick={onDelete}
				disabled={isUpdating}
				class="rounded-full bg-red-100 p-1.5 text-red-600 transition-colors hover:bg-red-200 disabled:opacity-50 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50"
				aria-label="Delete service"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
					/>
				</svg>
			</button>
			<div class="flex-1 px-2 text-xs text-theme-muted">
				{#if teamMemberNames.length === 0}
					<span class="italic">No team assigned</span>
				{:else}
					{teamMemberNames.join(', ')}
				{/if}
			</div>
			<button
				onclick={onAddDispatch}
				disabled={isUpdating}
				class="rounded-full bg-green-100 p-1.5 text-green-600 transition-colors hover:bg-green-200 disabled:opacity-50 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50"
				aria-label="Add dispatch"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
				</svg>
			</button>
		</div>
	{:else if column === 'readyToAssign'}
		<!-- Ready to Assign: Staged team members + Add button -->
		<div class="mb-3 flex flex-wrap items-center gap-1.5">
			{#each stagedMembers as member (member.pk)}
				<span
					class="inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-700 dark:bg-blue-900/30 dark:text-blue-300"
				>
					{member.name}
					<button
						onclick={() => onUnstageTeamMember?.(member.pk)}
						class="ml-0.5 rounded-full p-0.5 hover:bg-blue-200 dark:hover:bg-blue-800"
						aria-label="Remove {member.name}"
					>
						<svg class="h-3 w-3" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M6 18L18 6M6 6l12 12"
							/>
						</svg>
					</button>
				</span>
			{/each}
			<!-- Add team member button -->
			<div class="relative">
				<button
					onclick={(e) => {
						e.stopPropagation();
						onToggleDropdown?.();
					}}
					class="inline-flex items-center gap-0.5 rounded-full border border-dashed border-blue-300 px-2 py-0.5 text-xs font-medium text-blue-500 transition-colors hover:border-blue-400 hover:bg-blue-50 hover:text-blue-600 dark:border-blue-600 dark:text-blue-400 dark:hover:border-blue-500 dark:hover:bg-blue-900/20"
					aria-label="Add team member"
				>
					<svg class="h-3 w-3" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 6v6m0 0v6m0-6h6m-6 0H6"
						/>
					</svg>
					Add
				</button>
				{#if isDropdownOpen}
					<!-- svelte-ignore a11y_click_events_have_key_events -->
					<div
						role="menu"
						tabindex="-1"
						onclick={(e) => e.stopPropagation()}
						class="absolute top-full left-0 z-20 mt-1 w-48 rounded-lg border border-theme bg-theme-card py-1 shadow-lg"
					>
						{#if availableMembers.length === 0}
							<div class="px-3 py-2 text-sm text-theme-muted italic">No available members</div>
						{:else}
							{#each availableMembers as member (member.pk)}
								<button
									onclick={() => onStageTeamMember?.(member.pk)}
									class="block w-full interactive px-3 py-2 text-left text-sm text-theme"
								>
									{member.name}
								</button>
							{/each}
						{/if}
					</div>
				{/if}
			</div>
		</div>

		<div class="flex items-center justify-between border-t border-theme pt-2">
			<button
				onclick={onRemoveDispatch}
				disabled={isUpdating}
				class="rounded-full bg-red-100 p-1.5 text-red-600 transition-colors hover:bg-red-200 disabled:opacity-50 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50"
				aria-label="Remove dispatch"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M15 19l-7-7 7-7"
					/>
				</svg>
			</button>
			<button
				onclick={onSubmitStaged}
				disabled={!hasStaged || isUpdating}
				class="rounded-full p-1.5 transition-colors disabled:opacity-30 {hasStaged
					? 'bg-green-100 text-green-600 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50'
					: 'bg-theme-secondary text-theme-muted'}"
				aria-label="Assign team members"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
				</svg>
			</button>
		</div>
	{:else}
		<!-- Assigned column footer -->
		<div class="flex items-center justify-between border-t border-theme pt-2">
			<button
				onclick={onRemoveNonDispatch}
				disabled={isUpdating}
				class="rounded-full bg-red-100 p-1.5 text-red-600 transition-colors hover:bg-red-200 disabled:opacity-50 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50"
				aria-label="Remove team members"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M15 19l-7-7 7-7"
					/>
				</svg>
			</button>
			<div class="text-xs text-theme-muted">
				<span class="font-medium">Team:</span>
				{nonDispatchTeamMemberNames.join(', ')}
			</div>
		</div>
	{/if}
</div>
