import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach } from 'vitest';

const mockDelete = vi.fn();

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    useForm: vi.fn(() => ({
      data: { password: '' },
      setData: vi.fn(),
      delete: mockDelete,
      processing: false,
      errors: {},
      reset: vi.fn(),
    })),
    Head: () => null,
  };
});

import DeleteUserForm from './DeleteUserForm';

describe('DeleteUserForm', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders the Delete Account button', () => {
    render(<DeleteUserForm />);
    expect(screen.getByRole('button', { name: /delete account/i })).toBeInTheDocument();
  });

  it('dialog is hidden initially', () => {
    render(<DeleteUserForm />);
    expect(screen.queryByText(/this action cannot be undone/i)).not.toBeInTheDocument();
  });

  it('opens the confirmation dialog when Delete Account is clicked', async () => {
    const user = userEvent.setup();
    render(<DeleteUserForm />);

    await user.click(screen.getByRole('button', { name: /delete account/i }));

    expect(screen.getByText(/this action cannot be undone/i)).toBeInTheDocument();
    expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
  });

  it('submit button is disabled when password is empty', async () => {
    const user = userEvent.setup();
    render(<DeleteUserForm />);

    await user.click(screen.getByRole('button', { name: /delete account/i }));

    // The submit button inside the dialog should be disabled when no password
    const submitButton = screen.getByRole('button', { name: /^delete account$/i });
    expect(submitButton).toBeDisabled();
  });

  it('closes the dialog when Cancel is clicked', async () => {
    const user = userEvent.setup();
    render(<DeleteUserForm />);

    await user.click(screen.getByRole('button', { name: /delete account/i }));
    expect(screen.getByText(/this action cannot be undone/i)).toBeInTheDocument();

    await user.click(screen.getByRole('button', { name: /cancel/i }));
    expect(screen.queryByText(/this action cannot be undone/i)).not.toBeInTheDocument();
  });
});
