import { test, expect } from '@playwright/test';

async function navigateToEditPage(page) {
    await page.goto('/services');
    await page.waitForLoadState('networkidle');

    const editButton = page.getByTestId('service-list-edit-button').first();
    const hasEditableService = await editButton.isVisible().catch(() => false);

    if (!hasEditableService) {
        return false;
    }

    await editButton.click();
    await page.waitForLoadState('networkidle');
    return true;
}

test('edit seite zeigt ablauf sektion statt accordion bloecke', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    await expect(page).toHaveURL(/.*services\/\d+\/edit/);

    const agendaSection = page.getByTestId('agenda-section');
    const emptyState = page.getByText('Keine Ablauf-Elemente vorhanden');
    const hasAgenda = await agendaSection.isVisible().catch(() => false);
    const hasEmptyState = await emptyState.isVisible().catch(() => false);

    expect(hasAgenda || hasEmptyState).toBe(true);

    const blockToggles = page.getByTestId('service-edit-block-toggle');
    const toggleCount = await blockToggles.count();
    expect(toggleCount).toBe(0);
});

test('informations block ist oben sichtbar', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const informationBlock = page.getByTestId('information-block');
    await expect(informationBlock).toBeVisible();
});

test('ablauf ueberschrift ist sichtbar', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    await expect(page.getByText('Ablauf')).toBeVisible();
});

test('agenda items zeigen korrekte elemente oder empty state', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const agendaSection = page.getByTestId('agenda-section');
    const emptyState = page.getByText('Keine Ablauf-Elemente vorhanden');

    const hasAgenda = await agendaSection.isVisible().catch(() => false);
    const hasEmptyState = await emptyState.isVisible().catch(() => false);

    if (hasEmptyState) {
        await expect(page.getByText('Bitte synchronisiere die Daten zuerst')).toBeVisible();
        return;
    }

    expect(hasAgenda).toBe(true);

    const agendaRows = page.getByTestId('agenda-item-row');
    const songItems = page.getByTestId('song-agenda-item');
    const headerItems = page.getByTestId('agenda-header-item');

    const rowCount = await agendaRows.count();
    const songCount = await songItems.count();
    const headerCount = await headerItems.count();

    expect(rowCount + songCount + headerCount).toBeGreaterThan(0);
});

test('header items zeigen titel als ueberschrift', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const headerItems = page.getByTestId('agenda-header-item');
    const headerCount = await headerItems.count();

    if (headerCount === 0) {
        test.skip();
    }

    const firstHeader = headerItems.first();
    await expect(firstHeader).toBeVisible();
    const headerText = await firstHeader.textContent();
    expect(headerText?.trim().length).toBeGreaterThan(0);
});

test('song agenda items zeigen songtitel', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const songItems = page.getByTestId('song-agenda-item');
    const songCount = await songItems.count();

    if (songCount === 0) {
        test.skip();
    }

    const firstSong = songItems.first();
    await expect(firstSong).toBeVisible();

    const songTitle = firstSong.getByTestId('song-agenda-title');
    await expect(songTitle).toBeVisible();
    const titleText = await songTitle.textContent();
    expect(titleText?.trim().length).toBeGreaterThan(0);
});

test('song agenda items zeigen arrangement pill wenn zugeordnet', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const arrangementPills = page.getByTestId('arrangement-pill');
    const pillCount = await arrangementPills.count();

    if (pillCount === 0) {
        test.skip();
    }

    const firstPill = arrangementPills.first();
    await expect(firstPill).toBeVisible();
});

test('song agenda item zeigt arrangement bearbeiten button', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const editArrangementBtn = page.getByTestId('song-edit-arrangement');
    const hasBtn = await editArrangementBtn.first().isVisible().catch(() => false);

    if (!hasBtn) {
        test.skip();
    }

    await expect(editArrangementBtn.first()).toBeVisible();
});

test('generische agenda items zeigen titel', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const agendaRows = page.getByTestId('agenda-item-row');
    const rowCount = await agendaRows.count();

    if (rowCount === 0) {
        test.skip();
    }

    const firstRow = agendaRows.first();
    await expect(firstRow).toBeVisible();

    const itemTitle = firstRow.getByTestId('agenda-item-title');
    await expect(itemTitle).toBeVisible();
    expect(await itemTitle.textContent()).toBeTruthy();
});

test('nicht zugeordnete songs zeigen erstellung anfragen button', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const requestBtn = page.getByTestId('song-request-creation');
    const hasUnmatched = await requestBtn.first().isVisible().catch(() => false);

    if (!hasUnmatched) {
        test.skip();
    }

    await expect(requestBtn.first()).toBeVisible();
});

test('song suche und manuelle zuordnung sichtbar bei nicht zugeordnetem song', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const searchInput = page.getByTestId('song-search-input');
    const hasSearch = await searchInput.first().isVisible().catch(() => false);

    if (!hasSearch) {
        test.skip();
    }

    await expect(searchInput.first()).toBeVisible();

    const assignBtn = page.getByTestId('song-assign-button');
    await expect(assignBtn.first()).toBeVisible();
});

test('uebersetzungs checkbox sichtbar bei songs mit uebersetzung', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const translationCheckbox = page.getByTestId('song-translation-checkbox');
    const hasTranslation = await translationCheckbox.first().isVisible().catch(() => false);

    if (!hasTranslation) {
        test.skip();
    }

    const initialState = await translationCheckbox.first().isChecked();

    await translationCheckbox.first().click();
    await page.waitForTimeout(300);

    const toggledState = await translationCheckbox.first().isChecked();
    expect(toggledState).not.toBe(initialState);

    await translationCheckbox.first().click();
    await page.waitForTimeout(300);

    const restoredState = await translationCheckbox.first().isChecked();
    expect(restoredState).toBe(initialState);
});

test('sticky action bar ist sichtbar', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const actionBar = page.getByTestId('service-edit-action-bar');
    await expect(actionBar).toBeVisible();

    const inProgress = page.getByText('In Bearbeitung');
    const finalized = page.getByText('Abgeschlossen');

    const hasInProgress = await inProgress.isVisible().catch(() => false);
    const hasFinalized = await finalized.isVisible().catch(() => false);

    expect(hasInProgress || hasFinalized).toBe(true);
});

test('abschliessen button in action bar sichtbar', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const finalizeBtn = page.getByTestId('service-edit-finalize-button');
    const hasFinalizeBtn = await finalizeBtn.isVisible().catch(() => false);

    if (!hasFinalizeBtn) {
        const reopenBtn = page.getByTestId('service-edit-reopen-button');
        await expect(reopenBtn).toBeVisible();
        return;
    }

    await expect(finalizeBtn).toBeVisible();
    await expect(finalizeBtn).toContainText('Abschließen');

    const finalizeDownloadBtn = page.getByTestId('service-edit-finalize-download-button');
    await expect(finalizeDownloadBtn).toBeVisible();
});

test('zurueck button navigiert zur service liste', async ({ page }) => {
    const navigated = await navigateToEditPage(page);
    if (!navigated) {
        test.skip();
    }

    const backBtn = page.getByTestId('service-edit-back-icon-button');
    await expect(backBtn).toBeVisible();

    await backBtn.click();
    await page.waitForLoadState('networkidle');

    await expect(page).toHaveURL(/.*services$/);
});
