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('$lib/api/me', () => ({
  updateProfile: vi.fn(),
  changePassword: vi.fn(),
  // Default to a resolved value so the page's $effect doesn't crash
  // on `.then()` of undefined when individual tests don't override.
  getAPIToken: vi.fn().mockResolvedValue({ api_token: '' }),
  regenerateAPIToken: vi.fn()
}));

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

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()
    );
  });
});

// Shared setup for cards that don't need LB state
function setupPage() {
  (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());
  (getAPIToken as ReturnType<typeof vi.fn>).mockResolvedValue({ api_token: 'tok_abc123' });
}

describe('Settings page — Profile card', () => {
  test('Save profile calls updateProfile with form values', async () => {
    setupPage();
    (updateProfile as ReturnType<typeof vi.fn>).mockResolvedValue({});
    render(SettingsPage);
    await fireEvent.input(screen.getByLabelText(/display name/i), { target: { value: 'Alice' } });
    await fireEvent.input(screen.getByLabelText(/email/i), { target: { value: 'alice@example.com' } });
    await fireEvent.click(screen.getByRole('button', { name: /save profile/i }));
    await waitFor(() =>
      expect(updateProfile).toHaveBeenCalledWith(
        expect.objectContaining({ display_name: 'Alice', email: 'alice@example.com' })
      )
    );
  });

  test('Save profile shows toast on success', async () => {
    setupPage();
    (updateProfile as ReturnType<typeof vi.fn>).mockResolvedValue({});
    render(SettingsPage);
    await fireEvent.click(screen.getByRole('button', { name: /save profile/i }));
    await waitFor(() => expect(screen.getByTestId('toast').textContent).toMatch(/profile saved/i));
  });
});

describe('Settings page — Password card', () => {
  test('mismatched passwords show toast and do not call changePassword', async () => {
    setupPage();
    render(SettingsPage);
    await fireEvent.input(screen.getByLabelText(/current password/i), { target: { value: 'oldpw1234' } });
    await fireEvent.input(screen.getByLabelText(/new password/i), { target: { value: 'newpw1234' } });
    await fireEvent.input(screen.getByLabelText(/confirm/i), { target: { value: 'different1' } });
    await fireEvent.click(screen.getByRole('button', { name: /change password/i }));
    expect(changePassword).not.toHaveBeenCalled();
    await waitFor(() => expect(screen.getByTestId('toast').textContent).toMatch(/do not match/i));
  });

  test('matched passwords call changePassword(current, new)', async () => {
    setupPage();
    (changePassword as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
    render(SettingsPage);
    await fireEvent.input(screen.getByLabelText(/current password/i), { target: { value: 'oldpw1234' } });
    await fireEvent.input(screen.getByLabelText(/new password/i), { target: { value: 'newpw1234' } });
    await fireEvent.input(screen.getByLabelText(/confirm/i), { target: { value: 'newpw1234' } });
    await fireEvent.click(screen.getByRole('button', { name: /change password/i }));
    await waitFor(() =>
      expect(changePassword).toHaveBeenCalledWith('oldpw1234', 'newpw1234')
    );
  });
});

describe('Settings page — API Token card', () => {
  test('first click on Regenerate shows "Click again to confirm"', async () => {
    setupPage();
    render(SettingsPage);
    await fireEvent.click(screen.getByRole('button', { name: /regenerate/i }));
    await waitFor(() =>
      expect(screen.getByRole('button', { name: /click again to confirm/i })).toBeInTheDocument()
    );
    expect(regenerateAPIToken).not.toHaveBeenCalled();
  });

  test('second click within 5s calls regenerateAPIToken', async () => {
    setupPage();
    (regenerateAPIToken as ReturnType<typeof vi.fn>).mockResolvedValue({ api_token: 'new_tok_xyz' });
    render(SettingsPage);
    await fireEvent.click(screen.getByRole('button', { name: /regenerate/i }));
    await waitFor(() =>
      expect(screen.getByRole('button', { name: /click again to confirm/i })).toBeInTheDocument()
    );
    await fireEvent.click(screen.getByRole('button', { name: /click again to confirm/i }));
    await waitFor(() => expect(regenerateAPIToken).toHaveBeenCalled());
  });
});
