import { Head, useForm } from '@inertiajs/react';
import { Info } from 'lucide-react';
import type { FormEvent } from 'react';
import SiteSettingsController from '@/actions/App/Http/Controllers/Admin/SiteSettingsController';
import { CharCount } from '@/components/admin/char-count';
import { TextField } from '@/components/admin/field';
import { FormSection } from '@/components/admin/form-section';
import { ImageField } from '@/components/admin/image-field';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import { SaveBar } from '@/components/admin/save-bar';
import { TranslatedField } from '@/components/admin/translated-field';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { useEditingLocale } from '@/hooks/use-editing-locale';
import { translationOf } from '@/lib/translations';
import type { FormErrors, Translations } from '@/types';

/** The stored settings, grouped like their keys ("contact.phone" → contact.phone). */
type Stored = {
    general: { name: string; tagline: Translations; founded_year: string };
    contact: {
        phone: string;
        whatsapp: string;
        email: string;
        address: Translations;
        city: string;
        postal_code: string;
        country: string;
        latitude: string;
        longitude: string;
        map_url: string;
        hours: Translations;
    };
    /** Profile URL by network key (instagram, facebook, …). */
    social: Record<string, string>;
    seo: {
        description: Translations;
        google_site_verification: string;
        bing_site_verification: string;
    };
    legal: { company_name: string; license_no: string };
    /** Rating summary per platform: `${platform}_url`, `_rating`, `_count`. */
    reviews: Record<string, string>;
};

/** The state the form edits: the settings plus the pending image changes. */
type Values = Omit<Stored, 'general' | 'seo'> & {
    general: Stored['general'] & {
        logo: File | null;
        logo_dark: File | null;
    };
    seo: Stored['seo'] & { default_image: File | null };
    /** Paths of the image settings whose stored file is to be deleted. */
    remove: string[];
};

type Group = 'general' | 'contact' | 'social' | 'seo' | 'legal' | 'reviews';

type Props = {
    values: Stored;
    /** Public path of every stored image by setting path; null when unset. */
    images: Record<string, string | null>;
    /** Social networks, in display order. */
    networks: string[];
    /** Review platforms whose rating summary is entered here, in display order. */
    reviewPlatforms: string[];
    /** What the site shows while a setting is empty. */
    defaults: {
        name: string;
        tagline: Translations;
        description: Translations;
        /** Brand logo files under public/ (null while missing). */
        logo: string | null;
        logo_dark: string | null;
    };
};

const NETWORK_NAMES: Record<string, string> = {
    instagram: 'Instagram',
    facebook: 'Facebook',
    youtube: 'YouTube',
    linkedin: 'LinkedIn',
    tiktok: 'TikTok',
    x: 'X',
};

const PLATFORM_NAMES: Record<string, string> = {
    google: 'Google',
    trustpilot: 'Trustpilot',
};

const PLATFORM_PAGES: Record<string, string> = {
    google: 'Google İşletme Profili yorum sayfasının adresi (https://…).',
    trustpilot: 'Kliniğin Trustpilot yorum sayfasının adresi (https://…).',
};

const DESCRIPTION_MAX = 160;

export default function SiteSettingsEdit({
    values,
    images,
    networks,
    reviewPlatforms,
    defaults,
}: Props) {
    const { locales, locale, setLocale, revealErrors } = useEditingLocale();

    const form = useForm<Values>({
        ...values,
        general: { ...values.general, logo: null, logo_dark: null },
        seo: { ...values.seo, default_image: null },
        remove: [],
    });
    const { data } = form;
    const errors: FormErrors = form.errors;

    const set = <G extends Group>(
        group: G,
        changes: Partial<Values[G]>,
    ): void => {
        form.setData((current) => ({
            ...current,
            [group]: { ...current[group], ...changes },
        }));
    };

    /** Mark (or unmark) the stored image of a setting for deletion. */
    const setRemoved = (path: string, removed: boolean): void => {
        form.setData((current) => ({
            ...current,
            remove: removed
                ? [...current.remove.filter((item) => item !== path), path]
                : current.remove.filter((item) => item !== path),
        }));
    };

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

        // Files cannot travel in a PUT body: post with a spoofed method.
        const { action, method } = SiteSettingsController.update.form();

        form.submit(method, action, {
            preserveScroll: true,
            onError: revealErrors,
            // The uploads are stored now; the form starts clean again.
            onSuccess: () =>
                form.setData((current) => ({
                    ...current,
                    general: {
                        ...current.general,
                        logo: null,
                        logo_dark: null,
                    },
                    seo: { ...current.seo, default_image: null },
                    remove: [],
                })),
        });
    };

    return (
        <>
            <Head title="Site ayarları" />

            <PageContainer>
                <PageHeader
                    title="Site ayarları"
                    description="Sitenin her sayfasında kullanılan marka, iletişim ve SEO bilgileri. Boş bırakılan bir alan temizlenir; site o bilgiyi hiç göstermez, yerine başka bir şey uydurmaz."
                />

                <form
                    onSubmit={submit}
                    noValidate
                    className="flex flex-col gap-6"
                >
                    <SaveBar
                        locales={locales}
                        locale={locale}
                        onLocaleChange={setLocale}
                        errors={errors}
                        processing={form.processing}
                        dirty={form.isDirty}
                    />

                    <div className="grid max-w-4xl grid-cols-1 gap-6">
                        <FormSection
                            title="Genel"
                            description="Sitenin adı, sloganı ve logoları."
                        >
                            <TextField
                                id="general-name"
                                label="Site adı"
                                value={data.general.name}
                                onChange={(name) => set('general', { name })}
                                error={errors['general.name']}
                                placeholder={defaults.name}
                                hint={`Sayfa başlıklarının sonuna eklenir. Boş bırakılırsa “${defaults.name}” kullanılır.`}
                            />

                            <TranslatedField
                                name="general.tagline"
                                label="Slogan"
                                locale={locale}
                                value={data.general.tagline}
                                onChange={(tagline) =>
                                    set('general', { tagline })
                                }
                                errors={errors}
                                placeholder={defaults.tagline[locale.code]}
                                hint="Anasayfanın başlığında site adından sonra gelir. Boş bırakılırsa gri yazıyla gösterilen varsayılan kullanılır."
                            />

                            <TextField
                                id="general-founded-year"
                                label="Deneyimin başladığı yıl"
                                inputMode="numeric"
                                maxLength={4}
                                value={data.general.founded_year}
                                onChange={(founded_year) =>
                                    set('general', { founded_year })
                                }
                                error={errors['general.founded_year']}
                                autoComplete="off"
                                className="sm:max-w-xs"
                                hint="Anasayfada “… yıllık deneyim” olarak gösterilir; boş bırakılırsa gizlenir."
                            />

                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                <ImageField
                                    id="general-logo"
                                    label="Logo"
                                    current={images['general.logo'] ?? null}
                                    file={data.general.logo}
                                    removed={data.remove.includes(
                                        'general.logo',
                                    )}
                                    onSelect={(logo) =>
                                        set('general', { logo })
                                    }
                                    onRemove={(removed) =>
                                        setRemoved('general.logo', removed)
                                    }
                                    error={errors['general.logo']}
                                    fallback={defaults.logo}
                                    hint="Açık zeminde kullanılır. SVG, PNG, WebP ya da JPG; en fazla 1 MB. Yüklenmezse soluk gösterilen marka logosu kullanılır."
                                />

                                <ImageField
                                    id="general-logo-dark"
                                    label="Koyu zemin logosu"
                                    current={
                                        images['general.logo_dark'] ?? null
                                    }
                                    file={data.general.logo_dark}
                                    removed={data.remove.includes(
                                        'general.logo_dark',
                                    )}
                                    onSelect={(logo_dark) =>
                                        set('general', { logo_dark })
                                    }
                                    onRemove={(removed) =>
                                        setRemoved('general.logo_dark', removed)
                                    }
                                    error={errors['general.logo_dark']}
                                    fallback={defaults.logo_dark}
                                    hint="Koyu zeminde (üst ve alt bilgi) kullanılan açık renkli sürüm. SVG, PNG, WebP ya da JPG; en fazla 1 MB. Yüklenmezse soluk gösterilen marka logosu kullanılır."
                                    dark
                                />
                            </div>

                            <Alert>
                                <Info />
                                <AlertTitle>
                                    Renkler ve yazı tipleri burada değil
                                </AlertTitle>
                                <AlertDescription>
                                    <p>
                                        Marka renkleri, yazı tipleri ve köşe
                                        yuvarlaklıkları panelden değiştirilmez;
                                        sitenin tasarım belirteçleri{' '}
                                        <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">
                                            resources/css/site.css
                                        </code>{' '}
                                        dosyasındaki{' '}
                                        <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">
                                            @theme
                                        </code>{' '}
                                        bölümünde tanımlıdır ve geliştirici
                                        tarafından güncellenir.
                                    </p>
                                </AlertDescription>
                            </Alert>
                        </FormSection>

                        <FormSection
                            title="İletişim"
                            description="Üst ve alt bilgide, iletişim sayfasında ve arama motoru verisinde (JSON-LD) kullanılır."
                        >
                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                <TextField
                                    id="contact-phone"
                                    label="Telefon"
                                    type="tel"
                                    value={data.contact.phone}
                                    onChange={(phone) =>
                                        set('contact', { phone })
                                    }
                                    error={errors['contact.phone']}
                                    autoComplete="off"
                                    hint="Sitede yazıldığı gibi görünür; ülke koduyla yazın (+90 …)."
                                />

                                <TextField
                                    id="contact-whatsapp"
                                    label="WhatsApp numarası"
                                    type="tel"
                                    value={data.contact.whatsapp}
                                    onChange={(whatsapp) =>
                                        set('contact', { whatsapp })
                                    }
                                    error={errors['contact.whatsapp']}
                                    autoComplete="off"
                                    hint="Sitede bağlantı olarak gösterilmez: ziyaretçi önce ad ve telefonunu bırakır, sohbet bu numarayla ardından açılır. CRM formları açıkken numarayı CRM verir. Ülke koduyla yazın."
                                />

                                <TextField
                                    id="contact-email"
                                    label="E-posta"
                                    type="email"
                                    value={data.contact.email}
                                    onChange={(email) =>
                                        set('contact', { email })
                                    }
                                    error={errors['contact.email']}
                                    autoComplete="off"
                                />

                                <TextField
                                    id="contact-map-url"
                                    label="Harita bağlantısı"
                                    type="url"
                                    value={data.contact.map_url}
                                    onChange={(map_url) =>
                                        set('contact', { map_url })
                                    }
                                    error={errors['contact.map_url']}
                                    autoComplete="off"
                                    hint="Kliniğin harita uygulamasındaki paylaşım bağlantısı (https://…)."
                                />
                            </div>

                            <TranslatedField
                                name="contact.address"
                                label="Adres"
                                locale={locale}
                                value={data.contact.address}
                                onChange={(address) =>
                                    set('contact', { address })
                                }
                                errors={errors}
                                rows={3}
                                hint="Sokak, bina ve ilçe; birden çok satır yazılabilir."
                            />

                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-3">
                                <TextField
                                    id="contact-city"
                                    label="Şehir"
                                    value={data.contact.city}
                                    onChange={(city) =>
                                        set('contact', { city })
                                    }
                                    error={errors['contact.city']}
                                    autoComplete="off"
                                />

                                <TextField
                                    id="contact-postal-code"
                                    label="Posta kodu"
                                    value={data.contact.postal_code}
                                    onChange={(postal_code) =>
                                        set('contact', { postal_code })
                                    }
                                    error={errors['contact.postal_code']}
                                    autoComplete="off"
                                />

                                <TextField
                                    id="contact-country"
                                    label="Ülke kodu"
                                    value={data.contact.country}
                                    onChange={(country) =>
                                        set('contact', {
                                            country: country.toUpperCase(),
                                        })
                                    }
                                    error={errors['contact.country']}
                                    maxLength={2}
                                    autoComplete="off"
                                    hint="İki harfli ISO kodu; Türkiye için TR."
                                />
                            </div>

                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                <TextField
                                    id="contact-latitude"
                                    label="Enlem"
                                    inputMode="decimal"
                                    value={data.contact.latitude}
                                    onChange={(latitude) =>
                                        set('contact', { latitude })
                                    }
                                    error={errors['contact.latitude']}
                                    autoComplete="off"
                                    hint="Ondalık derece, nokta ile (−90 … 90). Boylamla birlikte girilir."
                                />

                                <TextField
                                    id="contact-longitude"
                                    label="Boylam"
                                    inputMode="decimal"
                                    value={data.contact.longitude}
                                    onChange={(longitude) =>
                                        set('contact', { longitude })
                                    }
                                    error={errors['contact.longitude']}
                                    autoComplete="off"
                                    hint="Ondalık derece, nokta ile (−180 … 180)."
                                />
                            </div>

                            <TranslatedField
                                name="contact.hours"
                                label="Çalışma saatleri"
                                locale={locale}
                                value={data.contact.hours}
                                onChange={(hours) => set('contact', { hours })}
                                errors={errors}
                                rows={3}
                                hint="Her satıra bir gün aralığı yazılabilir."
                            />
                        </FormSection>

                        <FormSection
                            title="Sosyal medya"
                            description="Profil adreslerinin tamamını yazın (https://…). Yalnızca doldurulan ağların simgesi sitede gösterilir."
                        >
                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                {networks.map((network) => (
                                    <TextField
                                        key={network}
                                        id={`social-${network}`}
                                        label={
                                            NETWORK_NAMES[network] ?? network
                                        }
                                        type="url"
                                        value={data.social[network] ?? ''}
                                        onChange={(url) =>
                                            set('social', { [network]: url })
                                        }
                                        error={errors[`social.${network}`]}
                                        autoComplete="off"
                                    />
                                ))}
                            </div>
                        </FormSection>

                        <FormSection
                            title="SEO"
                            description="Sayfaların kendi SEO alanları boşken kullanılan varsayılanlar ve arama motoru doğrulamaları."
                        >
                            <TranslatedField
                                name="seo.description"
                                label="Varsayılan açıklama"
                                locale={locale}
                                value={data.seo.description}
                                onChange={(description) =>
                                    set('seo', { description })
                                }
                                errors={errors}
                                rows={3}
                                placeholder={defaults.description[locale.code]}
                                aside={
                                    <CharCount
                                        count={
                                            translationOf(
                                                data.seo.description,
                                                locale,
                                            ).length
                                        }
                                        max={DESCRIPTION_MAX}
                                    />
                                }
                                hint={`Kliniği tanıtan kısa metin; arama motoru verisinde kullanılır. En fazla ${DESCRIPTION_MAX} karakter önerilir. Boş bırakılırsa gri yazıyla gösterilen varsayılan kullanılır.`}
                            />

                            <ImageField
                                id="seo-default-image"
                                label="Paylaşım görseli"
                                current={images['seo.default_image'] ?? null}
                                file={data.seo.default_image}
                                removed={data.remove.includes(
                                    'seo.default_image',
                                )}
                                onSelect={(default_image) =>
                                    set('seo', { default_image })
                                }
                                onRemove={(removed) =>
                                    setRemoved('seo.default_image', removed)
                                }
                                error={errors['seo.default_image']}
                                hint="Sayfalar sosyal medyada paylaşıldığında görünen görsel. Önerilen boyut 1200 × 630 piksel, en fazla 1 MB. Sosyal ağlar SVG göstermediği için PNG ya da JPG kullanın."
                            />

                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                <TextField
                                    id="seo-google"
                                    label="Google Search Console doğrulama kodu"
                                    value={data.seo.google_site_verification}
                                    onChange={(google_site_verification) =>
                                        set('seo', { google_site_verification })
                                    }
                                    error={
                                        errors['seo.google_site_verification']
                                    }
                                    autoComplete="off"
                                    spellCheck={false}
                                    hint="Doğrulama etiketinin “content” değeri; etiketin tamamı değil."
                                />

                                <TextField
                                    id="seo-bing"
                                    label="Bing Webmaster doğrulama kodu"
                                    value={data.seo.bing_site_verification}
                                    onChange={(bing_site_verification) =>
                                        set('seo', { bing_site_verification })
                                    }
                                    error={errors['seo.bing_site_verification']}
                                    autoComplete="off"
                                    spellCheck={false}
                                    hint="Doğrulama etiketinin “content” değeri; etiketin tamamı değil."
                                />
                            </div>
                        </FormSection>

                        <FormSection
                            title="Yasal"
                            description="Alt bilgide ve arama motoru verisinde gösterilen kurum bilgileri."
                        >
                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                <TextField
                                    id="legal-company-name"
                                    label="Tüzel kişi adı"
                                    value={data.legal.company_name}
                                    onChange={(company_name) =>
                                        set('legal', { company_name })
                                    }
                                    error={errors['legal.company_name']}
                                    autoComplete="off"
                                    hint="Kliniği işleten şirketin ya da kurumun resmî unvanı."
                                />

                                <TextField
                                    id="legal-license-no"
                                    label="Ruhsat / yetki belgesi numarası"
                                    value={data.legal.license_no}
                                    onChange={(license_no) =>
                                        set('legal', { license_no })
                                    }
                                    error={errors['legal.license_no']}
                                    autoComplete="off"
                                />
                            </div>
                        </FormSection>

                        <FormSection
                            title="Yorumlar"
                            description="Platformlardaki puan ve yorum sayısı. Puan ve sayı platformdan aynen kopyalanır ve elle güncellenir; adres doluysa sitede o platformun yorum sayfasına bağlantı gösterilir; puan ve yorum sayısı yalnızca ikisi birlikte doluysa eklenir."
                        >
                            {reviewPlatforms.map((platform) => {
                                const name =
                                    PLATFORM_NAMES[platform] ?? platform;

                                return (
                                    <fieldset
                                        key={platform}
                                        className="grid grid-cols-1 gap-6 sm:grid-cols-4"
                                    >
                                        <legend className="sr-only">
                                            {name}
                                        </legend>

                                        <TextField
                                            id={`reviews-${platform}-url`}
                                            label={`${name} yorum sayfası`}
                                            type="url"
                                            value={
                                                data.reviews[
                                                    `${platform}_url`
                                                ] ?? ''
                                            }
                                            onChange={(url) =>
                                                set('reviews', {
                                                    [`${platform}_url`]: url,
                                                })
                                            }
                                            error={
                                                errors[
                                                    `reviews.${platform}_url`
                                                ]
                                            }
                                            autoComplete="off"
                                            className="sm:col-span-2"
                                            hint={PLATFORM_PAGES[platform]}
                                        />

                                        <TextField
                                            id={`reviews-${platform}-rating`}
                                            label={`${name} puanı`}
                                            inputMode="decimal"
                                            value={
                                                data.reviews[
                                                    `${platform}_rating`
                                                ] ?? ''
                                            }
                                            onChange={(rating) =>
                                                set('reviews', {
                                                    [`${platform}_rating`]:
                                                        rating,
                                                })
                                            }
                                            error={
                                                errors[
                                                    `reviews.${platform}_rating`
                                                ]
                                            }
                                            autoComplete="off"
                                            hint="1.0 – 5.0, nokta ile."
                                        />

                                        <TextField
                                            id={`reviews-${platform}-count`}
                                            label={`${name} yorum sayısı`}
                                            inputMode="numeric"
                                            value={
                                                data.reviews[
                                                    `${platform}_count`
                                                ] ?? ''
                                            }
                                            onChange={(count) =>
                                                set('reviews', {
                                                    [`${platform}_count`]:
                                                        count,
                                                })
                                            }
                                            error={
                                                errors[
                                                    `reviews.${platform}_count`
                                                ]
                                            }
                                            autoComplete="off"
                                            hint="Tam sayı."
                                        />
                                    </fieldset>
                                );
                            })}
                        </FormSection>
                    </div>
                </form>
            </PageContainer>
        </>
    );
}

SiteSettingsEdit.layout = {
    breadcrumbs: [
        {
            title: 'Site ayarları',
            href: SiteSettingsController.edit(),
        },
    ],
};
