import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import Page from './+page.svelte';

const enhanceCaptureRef = vi.hoisted(() => ({ submitFn: undefined as unknown }));

vi.mock('$app/forms', () => ({
	enhance: (_el: HTMLFormElement, fn?: unknown) => {
		enhanceCaptureRef.submitFn = fn;
		return { destroy: vi.fn() };
	}
}));
vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() }));

import { beforeNavigate, goto } from '$app/navigation';

const groups = [
	{ id: 'g1', name: 'Editoren', permissions: ['WRITE_ALL'] },
	{ id: 'g2', name: 'Admins', permissions: ['ADMIN'] }
];

const baseData = {
	user: undefined,
	canWrite: true,
	canAnnotate: false,
	canBlogWrite: false,
	groups
};

afterEach(cleanup);

type SubmitFn = () => Promise<
	(opts: {
		result: { type: string; [key: string]: unknown };
		update: () => Promise<void>;
	}) => Promise<void>
>;

// ─── Rendering ────────────────────────────────────────────────────────────────

describe('Admin new user page – rendering', () => {
	it('renders the page heading', async () => {
		render(Page, { data: baseData, form: null });
		await expect.element(page.getByText(/Neuen Benutzer anlegen/i)).toBeInTheDocument();
	});

	it('renders the email input', async () => {
		render(Page, { data: baseData, form: null });
		const input = document.querySelector<HTMLInputElement>('input[name="email"]');
		expect(input).not.toBeNull();
	});

	it('renders group checkboxes for each available group', async () => {
		render(Page, { data: baseData, form: null });
		await expect.element(page.getByText('Editoren')).toBeInTheDocument();
		await expect.element(page.getByText('Admins')).toBeInTheDocument();
	});

	it('cancel link points to /admin/users', async () => {
		render(Page, { data: baseData, form: null });
		await expect
			.element(page.getByRole('link', { name: /Abbrechen/i }))
			.toHaveAttribute('href', '/admin/users');
	});

	it('renders the create button', async () => {
		render(Page, { data: baseData, form: null });
		await expect.element(page.getByRole('button', { name: /Erstellen/i })).toBeInTheDocument();
	});
});

// ─── Error display ────────────────────────────────────────────────────────────

describe('Admin new user page – error display', () => {
	it('shows the error message when form has an error', async () => {
		render(Page, { data: baseData, form: { error: 'Ein Fehler ist aufgetreten.' } });
		await expect.element(page.getByText('Ein Fehler ist aufgetreten.')).toBeInTheDocument();
	});

	it('does not show error section when form is null', async () => {
		render(Page, { data: baseData, form: null });
		await expect.element(page.getByText('Ein Fehler ist aufgetreten.')).not.toBeInTheDocument();
	});
});

// ─── Unsaved-changes guard ────────────────────────────────────────────────────

describe('Admin new user page – unsaved-changes guard', () => {
	beforeEach(() => {
		vi.clearAllMocks();
		enhanceCaptureRef.submitFn = undefined;
	});

	it('does not show unsaved warning initially', async () => {
		render(Page, { data: baseData, form: null });
		await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
	});

	it('cancels navigation and shows banner when form is dirty', async () => {
		render(Page, { data: baseData, form: null });
		const [callback] = vi.mocked(beforeNavigate).mock.calls[0];

		document
			.querySelector<HTMLInputElement>('input[name="email"]')!
			.dispatchEvent(new InputEvent('input', { bubbles: true }));

		const cancel = vi.fn();
		callback({ cancel, to: { url: new URL('http://localhost/admin/users') } });

		expect(cancel).toHaveBeenCalled();
		await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
	});

	it('does not cancel navigation when form is clean', async () => {
		render(Page, { data: baseData, form: null });
		const [callback] = vi.mocked(beforeNavigate).mock.calls[0];

		const cancel = vi.fn();
		callback({ cancel, to: { url: new URL('http://localhost/admin/users') } });

		expect(cancel).not.toHaveBeenCalled();
	});

	it('discard button calls goto with the target URL', async () => {
		render(Page, { data: baseData, form: null });
		const [callback] = vi.mocked(beforeNavigate).mock.calls[0];

		document
			.querySelector<HTMLInputElement>('input[name="email"]')!
			.dispatchEvent(new InputEvent('input', { bubbles: true }));

		callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users') } });

		await page.getByRole('button', { name: /verwerfen/i }).click();

		expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/users');
	});

	it('clears banner when enhance callback receives a redirect result', async () => {
		render(Page, { data: baseData, form: null });
		const [navCallback] = vi.mocked(beforeNavigate).mock.calls[0];

		document
			.querySelector<HTMLInputElement>('input[name="email"]')!
			.dispatchEvent(new InputEvent('input', { bubbles: true }));

		navCallback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users') } });
		await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();

		const innerFn = await (enhanceCaptureRef.submitFn as SubmitFn)();
		await innerFn({
			result: { type: 'redirect', location: '/admin/users', status: 303 },
			update: vi.fn().mockResolvedValue(undefined)
		});

		await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();

		const cancel = vi.fn();
		navCallback({ cancel, to: { url: new URL('http://localhost/admin/users') } });
		expect(cancel).not.toHaveBeenCalled();
	});

	it('keeps banner when enhance callback receives a failure result', async () => {
		render(Page, { data: baseData, form: null });
		const [navCallback] = vi.mocked(beforeNavigate).mock.calls[0];

		document
			.querySelector<HTMLInputElement>('input[name="email"]')!
			.dispatchEvent(new InputEvent('input', { bubbles: true }));

		navCallback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users') } });
		await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();

		const innerFn = await (enhanceCaptureRef.submitFn as SubmitFn)();
		await innerFn({
			result: { type: 'failure', status: 400, data: { error: 'E-Mail bereits vergeben' } },
			update: vi.fn().mockResolvedValue(undefined)
		});

		const cancel = vi.fn();
		navCallback({ cancel, to: { url: new URL('http://localhost/admin/users') } });
		expect(cancel).toHaveBeenCalled();
	});
});
