import { Wand2 } from 'lucide-react';
import type { ReactNode } from 'react';
import { Field } from '@/components/admin/field';
import { LocaleBadge } from '@/components/admin/locale-tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { SLUG_PATTERN, slugify } from '@/lib/slug';
import { withTranslation } from '@/lib/translations';
import type { FormErrors, LocaleOption, Translations } from '@/types';

type Props = {
    locale: LocaleOption;
    /** The slug in every language. */
    value: Translations;
    onChange: (value: Translations) => void;
    /** The name the slug is derived from, in every language. */
    source: Translations;
    errors: FormErrors;
    /** What precedes the slug in the page address, e.g. "/tedaviler/botoks/". */
    prefix: string;
    hint?: ReactNode;
    /** Label of the wand button; names the field the slug comes from. */
    generateLabel?: string;
};

/**
 * The address part ("slug") of a page in the language being edited.
 * Whatever is typed is turned into a valid slug on the fly; the wand
 * button derives it from the name again.
 */
export function SlugField({
    locale,
    value,
    onChange,
    source,
    errors,
    prefix,
    hint,
    generateLabel = 'Addan üret',
}: Props) {
    const id = `slug-${locale.code}`;
    const slug = value[locale.code] ?? '';
    const name = source[locale.code] ?? '';
    const error = errors[`slug.${locale.code}`];
    const malformed = slug !== '' && !SLUG_PATTERN.test(slug);

    const set = (text: string): void =>
        onChange(withTranslation(value, locale.code, text));

    return (
        <Field
            id={id}
            label={
                <>
                    Adres uzantısı
                    {locale.default && (
                        <span className="text-red-600 dark:text-red-400">
                            {' '}
                            *<span className="sr-only"> (zorunlu)</span>
                        </span>
                    )}
                    <LocaleBadge locale={locale} />
                </>
            }
            error={
                error ??
                (malformed
                    ? 'Yalnızca küçük harf, rakam ve tire kullanın; tire ile bitmemeli.'
                    : undefined)
            }
            hint={hint}
        >
            <div className="flex items-center gap-2">
                <div className="flex min-w-0 flex-1 items-center rounded-md border border-input shadow-xs focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50">
                    <span className="max-w-[50%] shrink-0 truncate border-r bg-muted/50 px-3 py-2 font-mono text-xs text-muted-foreground">
                        {prefix}
                    </span>
                    <Input
                        id={id}
                        value={slug}
                        onChange={(event) =>
                            set(slugify(event.target.value, { typing: true }))
                        }
                        onBlur={() => {
                            // Drop the hyphen kept while typing.
                            if (slugify(slug) !== slug) {
                                set(slugify(slug));
                            }
                        }}
                        aria-invalid={error || malformed ? true : undefined}
                        aria-describedby={hint ? `${id}-hint` : undefined}
                        autoCapitalize="none"
                        autoCorrect="off"
                        spellCheck={false}
                        className="rounded-l-none border-0 font-mono shadow-none focus-visible:ring-0"
                    />
                </div>
                <Button
                    type="button"
                    variant="outline"
                    size="icon"
                    disabled={slugify(name) === '' || slugify(name) === slug}
                    onClick={() => set(slugify(name))}
                    title={generateLabel}
                >
                    <Wand2 />
                    <span className="sr-only">
                        Adres uzantısını {generateLabel.toLocaleLowerCase('tr')}
                    </span>
                </Button>
            </div>
        </Field>
    );
}
