import { usePage } from '@inertiajs/react';
import { CharCount } from '@/components/admin/char-count';
import { TranslatedField } from '@/components/admin/translated-field';
import type { FormErrors, LocaleOption, Translations } from '@/types';

/** Recommended lengths (docs/SEO.md §3): what a result page shows in full. */
const TITLE_MAX = 60;
const DESCRIPTION_MIN = 120;
const DESCRIPTION_MAX = 165;

type Props = {
    locale: LocaleOption;
    title: Translations;
    description: Translations;
    onTitleChange: (value: Translations) => void;
    onDescriptionChange: (value: Translations) => void;
    errors: FormErrors;
    /** Title the page gets while the SEO title is empty. */
    fallbackTitle: string;
    /** Description the page gets while the SEO description is empty. */
    fallbackDescription: string;
    /** Address of the page in this language; null when it has none yet. */
    path: string | null;
};

/**
 * SEO title and description of the language being edited, with live
 * character counters and a preview of the search result. The counters and
 * the preview use the fallbacks while a field is empty, so they always
 * show what the page will really send.
 */
export function SeoFields({
    locale,
    title,
    description,
    onTitleChange,
    onDescriptionChange,
    errors,
    fallbackTitle,
    fallbackDescription,
    path,
}: Props) {
    const { site } = usePage().props;

    // The site appends its name to every page title.
    const suffix = ` | ${site.name}`;
    const shownTitle = (title[locale.code] ?? '').trim() || fallbackTitle;
    const shownDescription =
        (description[locale.code] ?? '').trim() || fallbackDescription;
    const fullTitle = shownTitle === '' ? '' : shownTitle + suffix;

    return (
        <>
            <TranslatedField
                name="seo_title"
                label="SEO başlığı"
                locale={locale}
                value={title}
                onChange={onTitleChange}
                errors={errors}
                placeholder={fallbackTitle}
                aside={<CharCount count={fullTitle.length} max={TITLE_MAX} />}
                hint={`Boş bırakılırsa gri yazıyla gösterilen başlık kullanılır. Sayaç, sona eklenen “${suffix.trim()}” ekini de sayar; yaklaşık ${TITLE_MAX} karakteri geçmemesi önerilir.`}
            />

            <TranslatedField
                name="seo_description"
                label="SEO açıklaması"
                locale={locale}
                value={description}
                onChange={onDescriptionChange}
                errors={errors}
                rows={3}
                placeholder={fallbackDescription}
                aside={
                    <CharCount
                        count={shownDescription.length}
                        min={DESCRIPTION_MIN}
                        max={DESCRIPTION_MAX}
                    />
                }
                hint={`Boş bırakılırsa gri yazıyla gösterilen metin kullanılır. ${DESCRIPTION_MIN}–${DESCRIPTION_MAX} karakter önerilir.`}
            />

            <SearchPreview
                site={site}
                title={fullTitle}
                description={shownDescription}
                path={path}
            />
        </>
    );
}

type PreviewProps = {
    site: { name: string; url: string };
    title: string;
    description: string;
    path: string | null;
};

/** An approximation of how the page is listed on a search results page. */
function SearchPreview({ site, title, description, path }: PreviewProps) {
    const host = site.url.replace(/^https?:\/\//, '');
    const trail =
        path === null ? [] : path.split('/').filter((part) => part !== '');

    return (
        <div className="grid grid-cols-1 gap-2">
            <p className="text-sm font-medium">Google önizlemesi</p>
            <div className="rounded-lg border bg-background p-4">
                {path === null ? (
                    <p className="text-sm text-muted-foreground">
                        Bu dilde sayfanın henüz bir adresi yok; ad ve adres
                        uzantısı girildiğinde önizleme burada görünür.
                    </p>
                ) : (
                    <div className="max-w-xl">
                        <div className="flex items-center gap-3">
                            <span
                                aria-hidden="true"
                                className="flex size-7 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-semibold uppercase"
                            >
                                {site.name.charAt(0)}
                            </span>
                            <div className="min-w-0 text-sm leading-tight">
                                <p className="truncate">{site.name}</p>
                                <p className="truncate text-xs text-muted-foreground">
                                    {[host, ...trail].join(' › ')}
                                </p>
                            </div>
                        </div>
                        <p className="mt-2 truncate text-lg leading-snug text-blue-700 dark:text-blue-400">
                            {title || '—'}
                        </p>
                        <p className="mt-1 line-clamp-2 text-sm text-muted-foreground">
                            {description || 'Açıklama girilmedi.'}
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
}
