import { useForm } from '@inertiajs/react';
import type { FormEvent, ReactNode } from 'react';
import { PostStatusBadge } from '@/components/admin/badges';
import type { PostStatus } from '@/components/admin/badges';
import { CharCount } from '@/components/admin/char-count';
import { SelectField, SwitchField, TextField } from '@/components/admin/field';
import { FormSection } from '@/components/admin/form-section';
import { MarkdownField } from '@/components/admin/markdown-field';
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 { followName } from '@/lib/slug';
import {
    missingLocales,
    shownTranslation,
    translationOf,
    withTranslation,
} from '@/lib/translations';
import type { FormErrors, Translations } from '@/types';

/** The state the form edits — exactly what the server validates. */
export type PostValues = {
    treatment_category_id: number | null;
    title: Translations;
    slug: Translations;
    excerpt: Translations;
    /** Markdown source of the post, per language. */
    body: Translations;
    seo_title: Translations;
    seo_description: Translations;
    is_published: boolean;
    /**
     * Date and time in the site's time zone ("YYYY-MM-DDTHH:mm"), or ''
     * while the post has no date.
     */
    published_at: string;
    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 PostFormOptions = {
    /** Categories by their name in the default language. */
    categories: { id: number; name: string }[];
    /** Address of the blog index per language; slugs are appended to it. */
    basePaths: Record<string, string>;
    /** Time zone the publish date is entered in, e.g. "Europe/Istanbul". */
    timezone: string;
    /** The current time in that zone, in the format of `published_at`. */
    now: string;
};

type Props = PostFormOptions & {
    values: PostValues;
    /** Where the form is sent: `PostController.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 post's cover). */
    footer?: ReactNode;
    saveLabel?: string;
};

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

/** Hard limit of the excerpt (PostRequest). */
const EXCERPT_MAX = 220;

/** "2026-11-11T14:30" → "11.11.2026 14:30", the way the panel writes dates. */
function displayDate(value: string): string {
    const [date, time = ''] = value.split('T');
    const [year, month, day] = date.split('-');

    return `${day}.${month}.${year} ${time}`.trim();
}

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

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

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

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

        form.submit(action, {
            preserveScroll: true,
            onError: revealErrors,
        });
    };

    const title = translationOf(data.title, locale);
    const slug = translationOf(data.slug, locale);
    const basePath = basePaths[locale.code] ?? '';

    // What saving the form as it stands leads to. Both dates are local
    // times in the same format, so they compare as text.
    const scheduled = data.published_at !== '' && data.published_at > now;
    const status: PostStatus = !data.is_published
        ? 'draft'
        : scheduled
          ? 'scheduled'
          : 'live';

    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.title, 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
                                ? 'Yazının blog listesinde ve sayfa başlığında görünen başlığı, adresi ve kısa açıklaması.'
                                : `${locale.name} başlık ve adres uzantısı girilmezse yazı ${locale.name} sitede hiç yer almaz.`
                        }
                    >
                        <TranslatedField
                            name="title"
                            label="Başlık"
                            locale={locale}
                            value={data.title}
                            onChange={changeTitle}
                            errors={errors}
                            required
                        />

                        <SlugField
                            locale={locale}
                            value={data.slug}
                            onChange={(value) => set('slug', value)}
                            source={data.title}
                            errors={errors}
                            prefix={`${basePath}/`}
                            generateLabel="Başlıktan üret"
                            hint={
                                <>
                                    {!locale.default && (
                                        <>
                                            Boş bırakılırsa yazı {locale.name}{' '}
                                            sitede hiç yer almaz.{' '}
                                        </>
                                    )}
                                    Yayındaki bir yazının 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={`Blog listesindeki kartlarda, yazının başlığının altında ve SEO açıklaması boşken arama sonuçlarında kullanılır. En çok ${EXCERPT_MAX} karakter.`}
                            aside={
                                <CharCount
                                    count={
                                        translationOf(data.excerpt, locale)
                                            .length
                                    }
                                    min={100}
                                    max={EXCERPT_MAX}
                                />
                            }
                        />

                        <SelectField
                            id="treatment_category_id"
                            label="Kategori"
                            value={
                                data.treatment_category_id === null
                                    ? NO_CATEGORY
                                    : String(data.treatment_category_id)
                            }
                            onChange={(id) =>
                                set(
                                    'treatment_category_id',
                                    id === NO_CATEGORY ? null : Number(id),
                                )
                            }
                            options={[
                                { value: NO_CATEGORY, label: 'Kategori yok' },
                                ...categories.map((item) => ({
                                    value: String(item.id),
                                    label: item.name,
                                })),
                            ]}
                            error={errors.treatment_category_id}
                            hint="İsteğe bağlıdır. Yazının ilgili olduğu uzmanlık alanı: yazı o kategorinin rengiyle gösterilir ve kategori sayfasına bağlantı verir."
                        />
                    </FormSection>

                    <FormSection
                        title="Yazı"
                        description={`Yazının ${locale.name} metni. Vaat, garanti ya da üstünlük ifadesi kullanmayın; bir işlemden söz ediyorsanız olası yan etkilerini de yazın.`}
                    >
                        <MarkdownField
                            name="body"
                            label="Metin (Markdown)"
                            locale={locale}
                            value={data.body}
                            onChange={(value) => set('body', value)}
                            errors={errors}
                            rows={30}
                            hint="“## Başlık” ile yazılan bölüm başlıkları, birden fazlaysa, yazının içindekiler listesini oluşturur."
                        />
                    </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,
                                      )) || title
                            }
                            fallbackDescription={
                                (locale.default
                                    ? ''
                                    : translationOf(
                                          data.seo_description,
                                          defaultLocale,
                                      )) ||
                                shownTranslation(
                                    data.excerpt,
                                    locale,
                                    defaultLocale,
                                )
                            }
                            path={
                                title !== '' && slug !== ''
                                    ? `${basePath}/${slug}`
                                    : null
                            }
                        />
                    </FormSection>

                    <FormSection
                        title="Yayın"
                        description="Bu ayarlar bütün diller için ortaktır."
                        aside={<PostStatusBadge status={status} />}
                    >
                        <SwitchField
                            id="is_published"
                            label="Yayında"
                            checked={data.is_published}
                            onChange={(published) =>
                                set('is_published', published)
                            }
                            error={errors.is_published}
                            hint="Kapalıyken yazı taslaktır: sitede, blog listesinde ve site haritasında görünmez."
                        />

                        <TextField
                            id="published_at"
                            label="Yayın tarihi"
                            type="datetime-local"
                            min="1971-01-01T00:00"
                            max="2037-12-31T23:59"
                            value={data.published_at}
                            onChange={(value) => set('published_at', value)}
                            error={errors.published_at}
                            className="sm:max-w-xs"
                            hint={`Site saatiyle (${timezone}). Boş bırakılırsa yazı, yayına alındığı anın tarihini alır. İleri bir tarih yazıyı zamanlar.`}
                        />

                        <p
                            aria-live="polite"
                            className="rounded-lg border bg-muted/40 px-4 py-3 text-sm"
                        >
                            {status === 'draft' &&
                                'Taslak: yazı sitede görünmez.'}
                            {status === 'scheduled' &&
                                `Zamanlandı: yazı ${displayDate(data.published_at)} tarihinde kendiliğinden yayına girer; o zamana kadar sitede görünmez.`}
                            {status === 'live' &&
                                (data.published_at === ''
                                    ? 'Yayında: yayın tarihi, yazının kaydedildiği an olur.'
                                    : `Yayında: yazı sitede ${displayDate(data.published_at)} tarihiyle gösterilir.`)}
                        </p>
                    </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>
    );
}
