import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeProvider } from '../../../theme';
import FormDialogShell from './FormDialogShell';

describe('<FormDialogShell/>', () => {
  const wrap = (ui: React.ReactNode) => render(<ThemeProvider>{ui}</ThemeProvider>);

  const baseProps = {
    open: true,
    title: 'Add patient',
    closeLabel: 'Close',
    discardTitle: 'Discard changes?',
    discardBody: 'Your changes will be lost.',
    discardConfirmLabel: 'Discard',
    discardCancelLabel: 'Keep editing',
  };

  it('renders the title and children', () => {
    wrap(
      <FormDialogShell {...baseProps} dirty={false} onClose={jest.fn()}>
        <div>form body</div>
      </FormDialogShell>,
    );
    expect(screen.getByText('Add patient')).toBeInTheDocument();
    expect(screen.getByText('form body')).toBeInTheDocument();
  });

  it('closes immediately when not dirty', () => {
    const onClose = jest.fn();
    wrap(
      <FormDialogShell {...baseProps} dirty={false} onClose={onClose}>
        <div />
      </FormDialogShell>,
    );
    fireEvent.click(screen.getByLabelText('Close'));
    expect(onClose).toHaveBeenCalledTimes(1);
  });

  it('shows a discard confirm instead of closing when dirty', () => {
    const onClose = jest.fn();
    wrap(
      <FormDialogShell {...baseProps} dirty onClose={onClose}>
        <div />
      </FormDialogShell>,
    );
    fireEvent.click(screen.getByLabelText('Close'));
    expect(onClose).not.toHaveBeenCalled();
    expect(screen.getByText('Discard changes?')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Discard' }));
    expect(onClose).toHaveBeenCalledTimes(1);
  });

  it('keeps editing (does not close) when the discard confirm is cancelled', () => {
    const onClose = jest.fn();
    wrap(
      <FormDialogShell {...baseProps} dirty onClose={onClose}>
        <div />
      </FormDialogShell>,
    );
    fireEvent.click(screen.getByLabelText('Close'));
    fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));
    expect(onClose).not.toHaveBeenCalled();
  });
});
