import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider } from '../../theme';

jest.mock('next-intl', () => ({
  useTranslations: () => (key: string) => key,
  useLocale: () => 'en',
}));

const PROVINCES = [{ id: 1, nameFa: 'تهران', nameEn: 'Tehran', sortOrder: 0 }];
const CITIES = [{ id: 101, provinceId: 1, nameFa: 'تهران', nameEn: 'Tehran', sortOrder: 0 }];
const DISTRICTS = [{ id: 1001, cityId: 101, nameFa: 'منطقه ۱', nameEn: 'District 1', sortOrder: 0 }];

jest.mock('@/services/geography', () => ({
  useProvinces: () => ({ data: PROVINCES, isLoading: false, isSuccess: true }),
  useCities: (provinceId: number | null) => ({ data: provinceId ? CITIES : [], isLoading: false, isSuccess: provinceId != null }),
  useDistricts: (cityId: number | null) => ({ data: cityId ? DISTRICTS : [], isLoading: false, isSuccess: cityId != null }),
}));

import AddressForm from './AddressForm';

describe('<AddressForm/> component', () => {
  it('blocks submit and flags city + pin + required text when empty', async () => {
    const user = userEvent.setup();
    const onSubmit = jest.fn();
    render(
      <ThemeProvider>
        <AddressForm onSubmit={onSubmit} />
      </ThemeProvider>,
    );
    await user.click(screen.getByRole('button', { name: 'save' }));
    expect(onSubmit).not.toHaveBeenCalled();
    expect(screen.getByText('title_required')).toBeInTheDocument();
    expect(screen.getByText('city_required')).toBeInTheDocument();
    expect(screen.getByText('line_required')).toBeInTheDocument();
    expect(screen.getByText('map_required')).toBeInTheDocument();
  });

  it('submits the mapped address input from an edit prefill', async () => {
    const user = userEvent.setup();
    const onSubmit = jest.fn();
    render(
      <ThemeProvider>
        <AddressForm
          initial={{
            title: 'Home',
            provinceId: 1,
            cityId: 101,
            districtId: 1001,
            addressLine: 'No. 5, Vali St',
            latitude: 35.7,
            longitude: 51.4,
            isPrimary: false,
          }}
          onSubmit={onSubmit}
        />
      </ThemeProvider>,
    );
    await user.click(screen.getByRole('button', { name: 'save' }));
    expect(onSubmit).toHaveBeenCalledTimes(1);
    expect(onSubmit).toHaveBeenCalledWith({
      title: 'Home',
      provinceId: 1,
      cityId: 101,
      districtId: 1001,
      addressLine: 'No. 5, Vali St',
      latitude: 35.7,
      longitude: 51.4,
      isPrimary: false,
    });
  });
});
