import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { readable, writable } from 'svelte/store';
import type { LBStatus } from '$lib/api/listenbrainz';

vi.mock('$lib/api/listenbrainz', () => ({
  createLBStatusQuery: vi.fn(),
  createTokenMutation: vi.fn(),
  createEnabledMutation: vi.fn(),
  setListenBrainzToken: vi.fn(),
  setListenBrainzEnabled: vi.fn()
}));

vi.mock('@tanstack/svelte-query', async (orig) => {
  const actual = (await orig()) as Record<string, unknown>;
  return {
    ...actual,
    useQueryClient: () => ({ invalidateQueries: vi.fn() })
  };
});

import SettingsPage from './+page.svelte';
import {
  createLBStatusQuery,
  createTokenMutation,
  createEnabledMutation,
  setListenBrainzToken,
  setListenBrainzEnabled
} from '$lib/api/listenbrainz';

function mockStatusStore(data: LBStatus) {
  return readable({ data, isPending: false, isError: false });
}

function mockMutationStore(mutateFn: (vars: unknown) => void = vi.fn()) {
  return readable({ isPending: false, mutate: mutateFn, mutateAsync: vi.fn() });
}

afterEach(() => vi.clearAllMocks());

describe('Settings page — ListenBrainz', () => {
  test('token-not-set state renders input + Save button', async () => {
    (createLBStatusQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockStatusStore({ enabled: false, token_set: false, last_scrobbled_at: null })
    );
    (createTokenMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    (createEnabledMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    render(SettingsPage);
    await waitFor(() =>
      expect(screen.getByPlaceholderText(/paste your lb token/i)).toBeInTheDocument()
    );
    expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
  });

  test('token-set state renders masked + Clear button', async () => {
    (createLBStatusQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockStatusStore({ enabled: false, token_set: true, last_scrobbled_at: null })
    );
    (createTokenMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    (createEnabledMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    render(SettingsPage);
    await waitFor(() => expect(screen.getByText(/\(set\)/)).toBeInTheDocument());
    expect(screen.getByText('clear')).toBeInTheDocument();
  });

  test('Save button calls setListenBrainzToken with typed value', async () => {
    (createLBStatusQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockStatusStore({ enabled: false, token_set: false, last_scrobbled_at: null })
    );
    const mutateFn = vi.fn();
    (createTokenMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore(mutateFn));
    (createEnabledMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    render(SettingsPage);
    const input = await screen.findByPlaceholderText(/paste your lb token/i);
    await fireEvent.input(input, { target: { value: 'mytoken' } });
    await fireEvent.click(screen.getByRole('button', { name: /save/i }));
    await waitFor(() => expect(mutateFn).toHaveBeenCalledWith('mytoken', expect.anything()));
  });

  test('Enabled checkbox is disabled when no token', async () => {
    (createLBStatusQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockStatusStore({ enabled: false, token_set: false, last_scrobbled_at: null })
    );
    (createTokenMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    (createEnabledMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    render(SettingsPage);
    const checkbox = await screen.findByRole('checkbox');
    expect(checkbox).toBeDisabled();
  });

  test('Last-scrobbled-at renders when present', async () => {
    (createLBStatusQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockStatusStore({ enabled: true, token_set: true, last_scrobbled_at: '2026-04-28T03:00:00Z' })
    );
    (createTokenMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    (createEnabledMutation as ReturnType<typeof vi.fn>).mockReturnValue(mockMutationStore());
    render(SettingsPage);
    await waitFor(() =>
      expect(screen.getByText(/last scrobbled:/i)).toBeInTheDocument()
    );
  });
});
