import { useForm } from '@inertiajs/react';
import type { FormEvent, ReactNode } from 'react';
import { CharCount } from '@/components/admin/char-count';
import {
    SelectField,
    SwitchField,
    TextareaField,
    TextField,
} from '@/components/admin/field';
import { FormSection } from '@/components/admin/form-section';
import {
    PairListEditor,
    StringListEditor,
} from '@/components/admin/list-editor';
import { PageContainer } from '@/components/admin/page-header';
import { ReviewSection } from '@/components/admin/review-section';
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 type { UseEditingLocaleReturn } from '@/hooks/use-editing-locale';
import { factLabel, zoneLabel } 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 treatment page in one language (App\Content\BodySchema). */
type Body = {
    lead: string;
    what: string[];
    who: string[];
    steps: TitleText[];
    aftercare: string[];
    risks: string[];
    results: string;
    faq: QuestionAnswer[];
};

/** The state the form edits — exactly what the server validates. */
export type TreatmentValues = {
    treatment_category_id: number | null;
    name: Translations;
    slug: Translations;
    excerpt: Translations;
    content: Record<string, Body>;
    /** Quick facts by key (duration, anesthesia, …), each translatable. */
    facts: Record<string, Translations>;
    seo_title: Translations;
    seo_description: Translations;
    zone: string | null;
    sort_order: number;
    is_featured: boolean;
    is_published: boolean;
    reviewed_by: string;
    /** YYYY-MM-DD, or '' when there is no review. */
    reviewed_at: string;
};

/** Choices and URL parts the server sends along with the form state. */
export type TreatmentFormOptions = {
    categories: {
        id: number;
        /** Name in the default language, for the drop-down. */
        name: string;
        names: Translations;
        slugs: Translations;
    }[];
    zones: string[];
    factKeys: string[];
    /** Address of the treatments index per language; slugs are appended to it. */
    basePaths: Record<string, string>;
};

type Props = TreatmentFormOptions & {
    values: TreatmentValues;
    /** Where the form is sent: `TreatmentController.store()` or `.update(id)`. */
    action: { url: string; method: 'post' | 'put' };
    /** State of the language switch; owned by the page so it survives a save. */
    editing: UseEditingLocaleReturn;
    /** The page header (title and actions), shown above the save bar. */
    header: ReactNode;
    /** Shown after the last section (e.g. the note on the page's media). */
    footer?: ReactNode;
    saveLabel?: string;
};

/** A zone is optional, but a Select item cannot have an empty value. */
const NO_ZONE = 'none';

/**
 * The treatment editor shared by the create and edit pages: every field
 * of a treatment, in the language chosen in the save bar.
 */
export function TreatmentForm({
    values,
    action,
    editing,
    header,
    footer,
    saveLabel,
    categories,
    zones,
    factKeys,
    basePaths,
}: Props) {
    const { locales, defaultLocale, locale, setLocale, revealErrors } = editing;
    const form = useForm<TreatmentValues>(values);
    const { data } = form;
    const errors: FormErrors = form.errors;

    const set = <K extends keyof TreatmentValues>(
        key: K,
        value: TreatmentValues[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(action, {
            preserveScroll: true,
            onError: revealErrors,
        });
    };

    const category = categories.find(
        (item) => item.id === data.treatment_category_id,
    );
    const categorySlug = category ? translationOf(category.slugs, locale) : '';
    const categoryName = category ? translationOf(category.names, locale) : '';
    const name = translationOf(data.name, locale);
    const slug = translationOf(data.slug, locale);
    const basePath = basePaths[locale.code] ?? '';

    // The title the page gets while the SEO title is empty (docs/SEO.md §3).
    const pageTitle =
        name === '' ? '' : [name, categoryName].filter(Boolean).join(' — ');

    return (
        <PageContainer>
            {/* Outside the form: its actions (delete) are forms of their own. */}
            {header}

            <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}
                    saveLabel={saveLabel}
                />

                <div className="grid max-w-4xl grid-cols-1 gap-6">
                    <FormSection
                        title="Temel bilgiler"
                        description={
                            locale.default
                                ? 'İşlemin listelerde ve sayfa başlığında görünen adı, adresi ve kısa açıklaması.'
                                : `${locale.name} ad ve adres uzantısı girilmezse işlem ${locale.name} sitede hiç yer almaz.`
                        }
                    >
                        <SelectField
                            id="treatment_category_id"
                            label="Kategori"
                            value={
                                data.treatment_category_id === null
                                    ? ''
                                    : String(data.treatment_category_id)
                            }
                            onChange={(id) =>
                                set('treatment_category_id', Number(id))
                            }
                            options={categories.map((item) => ({
                                value: String(item.id),
                                label: item.name,
                            }))}
                            placeholder="Kategori seçin"
                            error={errors.treatment_category_id}
                            hint="İşlemin adresi kategorisinin adresiyle başlar; kategori değişirse eski adres yenisine yönlendirilir."
                        />

                        <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}/${categorySlug || '…'}/`}
                            hint={
                                <>
                                    {!locale.default && (
                                        <>
                                            Boş bırakılırsa işlem {locale.name}{' '}
                                            sitede hiç yer almaz.{' '}
                                        </>
                                    )}
                                    {category && categorySlug === '' && (
                                        <>
                                            Seçili kategorinin {locale.name}{' '}
                                            adresi olmadığı için işlem bu dilde
                                            yayınlanamaz.{' '}
                                        </>
                                    )}
                                    Yayındaki bir işlemin adres uzantısı
                                    değişirse eski adres yeni adrese kalıcı
                                    olarak (301) yönlendirilir.
                                </>
                            }
                        />

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

                    {/* Keyed by language: each language has its own lists. */}
                    <FormSection
                        key={locale.code}
                        title="Sayfa içeriği"
                        description={`İşlem sayfasının ${locale.name} gövdesi. Boş bırakılan bölümler sayfada gösterilmez. Vaat, garanti ya da üstünlük ifadesi kullanmayın; olası yan etkileri yazın.`}
                    >
                        <TextareaField
                            id={`content-${locale.code}-lead`}
                            label="Giriş paragrafı"
                            value={body.lead}
                            onChange={(lead) => setBody({ lead })}
                            error={errors[`content.${locale.code}.lead`]}
                            rows={4}
                            lang={locale.code}
                            hint="Başlığın hemen altında görünen tanıtım."
                        />

                        <StringListEditor
                            name={`content.${locale.code}.what`}
                            label="Nedir?"
                            itemLabel="Paragraf"
                            items={body.what}
                            onChange={(what) => setBody({ what })}
                            errors={errors}
                            rows={5}
                            lang={locale.code}
                        />

                        <StringListEditor
                            name={`content.${locale.code}.who`}
                            label="Kimler için uygun?"
                            itemLabel="Madde"
                            items={body.who}
                            onChange={(who) => setBody({ who })}
                            errors={errors}
                            lang={locale.code}
                        />

                        <PairListEditor
                            name={`content.${locale.code}.steps`}
                            label="Uygulama adımları"
                            itemLabel="Adım"
                            items={body.steps}
                            onChange={(steps) => setBody({ steps })}
                            errors={errors}
                            first={{ key: 'title', label: 'Adım başlığı' }}
                            second={{ key: 'text', label: 'Açıklama' }}
                            lang={locale.code}
                        />

                        <StringListEditor
                            name={`content.${locale.code}.aftercare`}
                            label="İşlem sonrası"
                            itemLabel="Madde"
                            items={body.aftercare}
                            onChange={(aftercare) => setBody({ aftercare })}
                            errors={errors}
                            lang={locale.code}
                        />

                        <StringListEditor
                            name={`content.${locale.code}.risks`}
                            label="Olası yan etkiler"
                            itemLabel="Madde"
                            items={body.risks}
                            onChange={(risks) => setBody({ risks })}
                            errors={errors}
                            lang={locale.code}
                        />

                        <TextareaField
                            id={`content-${locale.code}-results`}
                            label="Sonuçlar ve kalıcılık"
                            value={body.results}
                            onChange={(results) => setBody({ results })}
                            error={errors[`content.${locale.code}.results`]}
                            rows={5}
                            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' }}
                            lang={locale.code}
                        />
                    </FormSection>

                    <FormSection
                        title="Hızlı bilgiler"
                        description="Sayfanın başındaki özet kutusu. Hepsi isteğe bağlıdır; boş bırakılan bilgi gösterilmez."
                    >
                        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                            {factKeys.map((fact) => (
                                <TranslatedField
                                    key={fact}
                                    name={`facts.${fact}`}
                                    label={factLabel(fact)}
                                    locale={locale}
                                    value={data.facts[fact] ?? {}}
                                    onChange={(value) =>
                                        form.setData((current) => ({
                                            ...current,
                                            facts: {
                                                ...current.facts,
                                                [fact]: value,
                                            },
                                        }))
                                    }
                                    errors={errors}
                                />
                            ))}
                        </div>
                    </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,
                                      )) || pageTitle
                            }
                            fallbackDescription={
                                (locale.default
                                    ? ''
                                    : translationOf(
                                          data.seo_description,
                                          defaultLocale,
                                      )) ||
                                shownTranslation(
                                    data.excerpt,
                                    locale,
                                    defaultLocale,
                                )
                            }
                            path={
                                name !== '' &&
                                slug !== '' &&
                                categorySlug !== ''
                                    ? `${basePath}/${categorySlug}/${slug}`
                                    : null
                            }
                        />
                    </FormSection>

                    <FormSection
                        title="Yayın ve sıralama"
                        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="zone"
                                label="Yüz / vücut haritası bölgesi"
                                value={data.zone ?? NO_ZONE}
                                onChange={(zone) =>
                                    set('zone', zone === NO_ZONE ? null : zone)
                                }
                                options={[
                                    { value: NO_ZONE, label: 'Bölge yok' },
                                    ...zones.map((zone) => ({
                                        value: zone,
                                        label: zoneLabel(zone),
                                    })),
                                ]}
                                error={errors.zone}
                                hint="Sitedeki yüz / vücut haritasında işlemin işaretlendiği nokta."
                            />

                            <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="Kategorisi içindeki yeri; küçük sayı önce gelir."
                            />
                        </div>

                        <SwitchField
                            id="is_featured"
                            label="Öne çıkar"
                            checked={data.is_featured}
                            onChange={(featured) =>
                                set('is_featured', featured)
                            }
                            error={errors.is_featured}
                            hint="Anasayfada, alanının panelinde ilk sıralarda gösterilir (panelde üç işlem görünür)."
                        />

                        <SwitchField
                            id="is_published"
                            label="Yayında"
                            checked={data.is_published}
                            onChange={(published) =>
                                set('is_published', published)
                            }
                            error={errors.is_published}
                            hint="Kapalıyken işlem sitede, menüde ve site haritasında görünmez."
                        />
                    </FormSection>

                    <ReviewSection
                        reviewedBy={data.reviewed_by}
                        reviewedAt={data.reviewed_at}
                        onReviewedByChange={(value) =>
                            set('reviewed_by', value)
                        }
                        onReviewedAtChange={(value) =>
                            set('reviewed_at', value)
                        }
                        errors={errors}
                    />

                    {footer}
                </div>
            </form>
        </PageContainer>
    );
}
