import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useState } from 'react';
import { describe, expect, it } from 'vitest';
import { CadastralCodeDisplay } from '@/components/cadastral-code-display';
import { CadastralCodeInput } from '@/components/cadastral-code-input';

describe('CadastralCodeDisplay', () => {
    it('renders padded segments from an unformatted code', () => {
        render(<CadastralCodeDisplay code="1-48-3-4" />);

        expect(screen.getByText('01')).toBeInTheDocument();
        expect(screen.getByText('0048')).toBeInTheDocument();
        expect(screen.getByText('003')).toBeInTheDocument();
        expect(screen.getByText('04')).toBeInTheDocument();
    });

    it('renders only three segments when sublote is missing', () => {
        render(<CadastralCodeDisplay code="1-48-3" />);

        expect(screen.getByText('01')).toBeInTheDocument();
        expect(screen.getByText('0048')).toBeInTheDocument();
        expect(screen.getByText('003')).toBeInTheDocument();
        expect(screen.getByText('-')).toBeInTheDocument();
    });
});

describe('CadastralCodeInput', () => {
    it('normalizes typed values and auto advances to the next block', async () => {
        const user = userEvent.setup();

        function Example() {
            const [value, setValue] = useState({
                codigo_zona: '',
                codigo_manzano: '',
            });

            return (
                <CadastralCodeInput
                    blocks={[
                        { key: 'codigo_zona', label: 'Zona', maxDigits: 2 },
                        {
                            key: 'codigo_manzano',
                            label: 'Manzano',
                            maxDigits: 4,
                        },
                    ]}
                    value={value}
                    onChange={(key, nextValue) =>
                        setValue((current) => ({
                            ...current,
                            [key]: nextValue,
                        }))
                    }
                />
            );
        }

        render(<Example />);

        const zonaInput = document.getElementById(
            'codigo_zona',
        ) as HTMLInputElement;
        const manzanoInput = document.getElementById(
            'codigo_manzano',
        ) as HTMLInputElement;

        await user.type(zonaInput, '01');

        expect(manzanoInput).toHaveFocus();
        expect(zonaInput).toHaveValue('01');

        await user.type(manzanoInput, '0048');
        await user.tab();

        expect(manzanoInput).toHaveValue('0048');
    });
});
