import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import Login from '../pages/Login'
import { useAuthStore } from '../store/auth'

vi.mock('../store/auth', () => ({
  useAuthStore: vi.fn(),
}))

const mockNavigate = vi.fn()
vi.mock('react-router-dom', async (importOriginal) => {
  const actual = await importOriginal()
  return {
    ...actual,
    useNavigate: () => mockNavigate,
  }
})

describe('Login page', () => {
  const mockLogin = vi.fn()

  beforeEach(() => {
    vi.clearAllMocks()
    useAuthStore.mockImplementation((selector) =>
      selector({ login: mockLogin })
    )
  })

  const renderLogin = () => render(<MemoryRouter><Login /></MemoryRouter>)

  it('renders login form', () => {
    renderLogin()
    expect(screen.getByPlaceholderText('your@email.com')).toBeInTheDocument()
    expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument()
    expect(screen.getByText('Войти')).toBeInTheDocument()
  })

  it('renders "С возвращением!" heading', () => {
    renderLogin()
    expect(screen.getByText('С возвращением!')).toBeInTheDocument()
  })

  it('renders forgot password link', () => {
    renderLogin()
    expect(screen.getByText('Забыли пароль?')).toBeInTheDocument()
  })

  it('renders register link', () => {
    renderLogin()
    expect(screen.getByText('Зарегистрируйся')).toBeInTheDocument()
  })

  it('submits login form successfully', async () => {
    mockLogin.mockResolvedValueOnce({})
    renderLogin()

    fireEvent.change(screen.getByPlaceholderText('your@email.com'), {
      target: { value: 'test@test.com' },
    })
    fireEvent.change(screen.getByPlaceholderText('••••••••'), {
      target: { value: 'password123' },
    })
    fireEvent.click(screen.getByText('Войти'))

    await waitFor(() => {
      expect(mockLogin).toHaveBeenCalledWith('test@test.com', 'password123')
      expect(mockNavigate).toHaveBeenCalledWith('/')
    })
  })

  it('shows error on login failure', async () => {
    mockLogin.mockRejectedValueOnce({ response: { data: { error: 'Неверный пароль' } } })
    renderLogin()

    fireEvent.change(screen.getByPlaceholderText('your@email.com'), {
      target: { value: 'test@test.com' },
    })
    fireEvent.change(screen.getByPlaceholderText('••••••••'), {
      target: { value: 'wrongpass' },
    })
    fireEvent.click(screen.getByText('Войти'))

    await waitFor(() => {
      expect(screen.getByText('Неверный пароль')).toBeInTheDocument()
    })
  })

  it('shows default error message on login failure', async () => {
    mockLogin.mockRejectedValueOnce(new Error('Network error'))
    renderLogin()

    fireEvent.change(screen.getByPlaceholderText('your@email.com'), {
      target: { value: 'test@test.com' },
    })
    fireEvent.change(screen.getByPlaceholderText('••••••••'), {
      target: { value: 'pass' },
    })
    fireEvent.click(screen.getByText('Войти'))

    await waitFor(() => {
      expect(screen.getByText('Ошибка входа')).toBeInTheDocument()
    })
  })

  it('toggles password visibility', () => {
    renderLogin()
    const passwordInput = screen.getByPlaceholderText('••••••••')
    expect(passwordInput.type).toBe('password')

    // Find the toggle button (Eye icon button)
    const toggleBtn = passwordInput.parentElement.querySelector('button[type="button"]')
    fireEvent.click(toggleBtn)
    expect(passwordInput.type).toBe('text')

    fireEvent.click(toggleBtn)
    expect(passwordInput.type).toBe('password')
  })
})
