import { Head, useForm } from '@inertiajs/react';
import type { FormEvent } from 'react';
import CategoryController from '@/actions/App/Http/Controllers/Admin/CategoryController';
import { CharCount } from '@/components/admin/char-count';
import { ExternalLink } from '@/components/admin/external-link';
import { SelectField, SwitchField, TextField } from '@/components/admin/field';
import { FormSection } from '@/components/admin/form-section';
import { MediaNote } from '@/components/admin/media-note';
import type { PageMedia } from '@/components/admin/media-note';
import {
    PairListEditor,
    StringListEditor,
} from '@/components/admin/list-editor';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import { SaveBar } from '@/components/admin/save-bar';
import { SeoFields } from '@/components/admin/seo-fields';
import { SlugField } from '@/components/admin/slug-field';
import { TranslatedField } from '@/components/admin/translated-field';
import { useEditingLocale } from '@/hooks/use-editing-locale';
import type { UseEditingLocaleReturn } from '@/hooks/use-editing-locale';
import { accentLabel } from '@/lib/content-labels';
import { followName } from '@/lib/slug';
import {
    missingLocales,
    shownTranslation,
    translationOf,
    withTranslation,
} from '@/lib/translations';
import type {
    FormErrors,
    QuestionAnswer,
    TitleText,
    Translations,
} from '@/types';

/** Body of a category page in one language (App\Content\BodySchema). */
type Body = {
    intro: string[];
    highlights: TitleText[];
    faq: QuestionAnswer[];
};

type Values = {
    name: Translations;
    slug: Translations;
    tagline: Translations;
    summary: Translations;
    content: Record<string, Body>;
    seo_title: Translations;
    seo_description: Translations;
    accent: string;
    sort_order: number;
    is_published: boolean;
};

type Props = {
    category: {
        id: number;
        key: string;
        name: string;
        treatmentCount: number;
        /** Address of the live page per language (absent where it is not live). */
        publicUrls: Record<string, string>;
        /** Changes whenever the category is saved. */
        version: number;
        /** Photo or video found for the page in the media library. */
        media: PageMedia | null;
    };
    values: Values;
    accents: string[];
    /** Address of the treatments index per language; slugs are appended to it. */
    basePaths: Record<string, string>;
};

export default function CategoryEdit(props: Props) {
    const editing = useEditingLocale();

    return (
        <>
            <Head title={`${props.category.name} · Kategoriler`} />

            {/* Remounted after a save, so the form shows what was stored. */}
            <CategoryForm
                key={props.category.version}
                editing={editing}
                {...props}
            />
        </>
    );
}

function CategoryForm({
    category,
    values,
    accents,
    basePaths,
    editing,
}: Props & { editing: UseEditingLocaleReturn }) {
    const { locales, defaultLocale, locale, setLocale, revealErrors } = editing;
    const form = useForm<Values>(values);
    const { data } = form;
    const errors: FormErrors = form.errors;

    const set = <K extends keyof Values>(key: K, value: Values[K]): void => {
        form.setData((current) => ({ ...current, [key]: value }));
    };

    const body = data.content[locale.code];

    const setBody = (changes: Partial<Body>): void => {
        form.setData((current) => ({
            ...current,
            content: {
                ...current.content,
                [locale.code]: { ...current.content[locale.code], ...changes },
            },
        }));
    };

    // A slug that was never saved follows the name; a saved one is a
    // public address and stays until the editor changes it.
    const changeName = (name: Translations): void => {
        form.setData((current) => ({
            ...current,
            name,
            slug: withTranslation(
                current.slug,
                locale.code,
                followName(
                    current.slug[locale.code] ?? '',
                    current.name[locale.code] ?? '',
                    name[locale.code] ?? '',
                    (values.slug[locale.code] ?? '') !== '',
                ),
            ),
        }));
    };

    const submit = (event: FormEvent<HTMLFormElement>): void => {
        event.preventDefault();

        form.submit(CategoryController.update(category.id), {
            preserveScroll: true,
            onError: revealErrors,
        });
    };

    const name = translationOf(data.name, locale);
    const slug = translationOf(data.slug, locale);
    const basePath = basePaths[locale.code] ?? '';
    const publicUrl = category.publicUrls[locale.code];

    return (
        <PageContainer>
            <PageHeader
                title={category.name}
                description={`Kategori anahtarı: ${category.key} · ${category.treatmentCount} işlem`}
                actions={
                    publicUrl && (
                        <ExternalLink href={publicUrl} className="text-sm">
                            Sitede gör ({locale.short})
                        </ExternalLink>
                    )
                }
            />

            <form onSubmit={submit} noValidate className="flex flex-col gap-6">
                <SaveBar
                    locales={locales}
                    locale={locale}
                    onLocaleChange={setLocale}
                    missing={missingLocales(locales, data.name, data.slug)}
                    errors={errors}
                    processing={form.processing}
                    dirty={form.isDirty}
                />

                <div className="grid max-w-4xl grid-cols-1 gap-6">
                    <FormSection
                        title="Temel bilgiler"
                        description={
                            locale.default
                                ? 'Kategorinin menüde, kartlarda ve sayfa başlığında görünen adı ve tanıtım metinleri.'
                                : `${locale.name} ad ve adres uzantısı girilmezse kategori ${locale.name} sitede hiç yer almaz.`
                        }
                    >
                        <TranslatedField
                            name="name"
                            label="Ad"
                            locale={locale}
                            value={data.name}
                            onChange={changeName}
                            errors={errors}
                            required
                        />

                        <SlugField
                            locale={locale}
                            value={data.slug}
                            onChange={(value) => set('slug', value)}
                            source={data.name}
                            errors={errors}
                            prefix={`${basePath}/`}
                            hint={
                                <>
                                    {!locale.default && (
                                        <>
                                            Boş bırakılırsa kategori{' '}
                                            {locale.name} sitede hiç yer
                                            almaz.{' '}
                                        </>
                                    )}
                                    Yayındaki bir kategorinin adres uzantısı
                                    değişirse eski adres (ve işlemlerinin eski
                                    adresleri) yeni adrese kalıcı olarak (301)
                                    yönlendirilir.
                                </>
                            }
                        />

                        <TranslatedField
                            name="tagline"
                            label="Slogan"
                            locale={locale}
                            value={data.tagline}
                            onChange={(value) => set('tagline', value)}
                            errors={errors}
                            hint="Kategori adının altında görünen tek cümle."
                        />

                        <TranslatedField
                            name="summary"
                            label="Özet"
                            locale={locale}
                            value={data.summary}
                            onChange={(value) => set('summary', value)}
                            errors={errors}
                            rows={3}
                            hint="Kategori kartlarında ve SEO açıklaması boşken arama sonuçlarında kullanılır."
                            aside={
                                <CharCount
                                    count={
                                        translationOf(data.summary, locale)
                                            .length
                                    }
                                    min={110}
                                    max={200}
                                />
                            }
                        />
                    </FormSection>

                    {/* Keyed by language: each language has its own lists. */}
                    <FormSection
                        key={locale.code}
                        title="Sayfa içeriği"
                        description={`Kategori sayfasının ${locale.name} gövdesi. Boş bırakılan bölümler sayfada gösterilmez.`}
                    >
                        <StringListEditor
                            name={`content.${locale.code}.intro`}
                            label="Giriş paragrafları"
                            itemLabel="Paragraf"
                            items={body.intro}
                            onChange={(intro) => setBody({ intro })}
                            errors={errors}
                            rows={4}
                            lang={locale.code}
                        />

                        <PairListEditor
                            name={`content.${locale.code}.highlights`}
                            label="Öne çıkanlar"
                            itemLabel="Madde"
                            hint="Kategori sayfasındaki kısa vurgu kutuları."
                            items={body.highlights}
                            onChange={(highlights) => setBody({ highlights })}
                            errors={errors}
                            first={{ key: 'title', label: 'Başlık' }}
                            second={{ key: 'text', label: 'Metin', rows: 2 }}
                            lang={locale.code}
                        />

                        <PairListEditor
                            name={`content.${locale.code}.faq`}
                            label="Sık sorulan sorular"
                            itemLabel="Soru"
                            hint="Sayfada görünen sorular, arama motorlarına da aynen bildirilir (FAQPage)."
                            items={body.faq}
                            onChange={(faq) => setBody({ faq })}
                            errors={errors}
                            first={{ key: 'q', label: 'Soru' }}
                            second={{ key: 'a', label: 'Cevap', rows: 3 }}
                            lang={locale.code}
                        />
                    </FormSection>

                    <FormSection
                        title="Arama motoru (SEO)"
                        description="Arama sonuçlarında görünen başlık ve açıklama."
                    >
                        <SeoFields
                            locale={locale}
                            title={data.seo_title}
                            description={data.seo_description}
                            onTitleChange={(value) => set('seo_title', value)}
                            onDescriptionChange={(value) =>
                                set('seo_description', value)
                            }
                            errors={errors}
                            fallbackTitle={
                                (locale.default
                                    ? ''
                                    : translationOf(
                                          data.seo_title,
                                          defaultLocale,
                                      )) || name
                            }
                            fallbackDescription={
                                (locale.default
                                    ? ''
                                    : translationOf(
                                          data.seo_description,
                                          defaultLocale,
                                      )) ||
                                shownTranslation(
                                    data.summary,
                                    locale,
                                    defaultLocale,
                                )
                            }
                            path={
                                name !== '' && slug !== ''
                                    ? `${basePath}/${slug}`
                                    : null
                            }
                        />
                    </FormSection>

                    <FormSection
                        title="Görünüm ve yayın"
                        description="Bu ayarlar bütün diller için ortaktır."
                    >
                        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                            <SelectField
                                id="accent"
                                label="Vurgu rengi"
                                value={data.accent}
                                onChange={(accent) => set('accent', accent)}
                                options={accents.map((accent) => ({
                                    value: accent,
                                    label: accentLabel(accent),
                                }))}
                                error={errors.accent}
                                hint="Kategorinin kartlarında ve sayfasında kullanılan renk teması."
                            />

                            <TextField
                                id="sort_order"
                                label="Sıra"
                                type="number"
                                min={0}
                                inputMode="numeric"
                                value={String(data.sort_order)}
                                onChange={(value) =>
                                    set('sort_order', Number(value) || 0)
                                }
                                error={errors.sort_order}
                                hint="Küçük sayı önce gelir (menü ve listeler)."
                            />
                        </div>

                        <SwitchField
                            id="is_published"
                            label="Yayında"
                            checked={data.is_published}
                            onChange={(published) =>
                                set('is_published', published)
                            }
                            error={errors.is_published}
                            hint="Kapatıldığında kategori ve bütün işlemleri siteden, menüden ve site haritasından kalkar."
                        />
                    </FormSection>

                    <MediaNote
                        media={category.media}
                        collection="categories"
                        name={category.key}
                    />
                </div>
            </form>
        </PageContainer>
    );
}

CategoryEdit.layout = (props: Props) => ({
    breadcrumbs: [
        { title: 'Kategoriler', href: CategoryController.index() },
        {
            title: props.category.name,
            href: CategoryController.edit(props.category.id),
        },
    ],
});
