import type { ReactNode } from 'react';
import { TextareaField, TextField } from '@/components/admin/field';
import { LocaleBadge } from '@/components/admin/locale-tabs';
import { withTranslation } from '@/lib/translations';
import type { FormErrors, LocaleOption, Translations } from '@/types';

type Props = {
    /** Field path without the locale: "name" reads errors["name.tr"]. */
    name: string;
    label: string;
    /** The language being edited (see useEditingLocale). */
    locale: LocaleOption;
    value: Translations;
    onChange: (value: Translations) => void;
    errors: FormErrors;
    hint?: ReactNode;
    /** Shown at the end of the label row, e.g. a character counter. */
    aside?: ReactNode;
    /** Required in the default language (other languages stay optional). */
    required?: boolean;
    /** Render a textarea with this many rows instead of a one-line input. */
    rows?: number;
    placeholder?: string;
    className?: string;
};

/**
 * One translatable field. It shows and edits the translation of the
 * language chosen in the form's language switch; the other translations
 * stay in `value` untouched.
 */
export function TranslatedField({
    name,
    label,
    locale,
    value,
    onChange,
    errors,
    hint,
    aside,
    required = false,
    rows,
    placeholder,
    className,
}: Props) {
    const shared = {
        id: `${name.replaceAll('.', '-')}-${locale.code}`,
        label: (
            <>
                {label}
                {required && locale.default && (
                    <span className="text-red-600 dark:text-red-400">
                        {' '}
                        *<span className="sr-only"> (zorunlu)</span>
                    </span>
                )}
                <LocaleBadge locale={locale} />
            </>
        ),
        value: value[locale.code] ?? '',
        onChange: (text: string) =>
            onChange(withTranslation(value, locale.code, text)),
        error: errors[`${name}.${locale.code}`],
        hint,
        aside,
        placeholder,
        className,
        lang: locale.code,
    };

    return rows === undefined ? (
        <TextField {...shared} />
    ) : (
        <TextareaField {...shared} rows={rows} />
    );
}
