import { useForm, Link, router, usePage } from '@inertiajs/react';
import { useRef, useState } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { useTranslator } from '@/lib/i18n';

interface Props {
    settings: any;
}

export default function AdminSettings({ settings }: Props) {
    const t = useTranslator();
    const { flash } = usePage<any>().props;
    const fileInput = useRef<HTMLInputElement | null>(null);
    const [testTo, setTestTo] = useState('');
    const [testing, setTesting] = useState(false);

    const EMAIL_PREVIEWS = [
        { key: 'save_the_date',       label: t('admin.preview_save_the_date') },
        { key: 'invite',              label: t('admin.preview_invite') },
        { key: 'rsvp_confirmation',   label: t('admin.preview_rsvp_confirmation') },
        { key: 'verification',        label: t('admin.preview_verification') },
        { key: 'password_reset',      label: t('admin.preview_password_reset') },
        { key: 'collaborator_invite', label: t('admin.preview_collaborator_invite') },
    ];

    const form = useForm({
        // Branding
        app_name: settings.app_name ?? '',
        app_logo_url: settings.app_logo_url ?? '',
        app_base_url: settings.app_base_url ?? '',
        support_email: settings.support_email ?? '',

        // Email — driver toggle
        mail_driver: settings.mail_driver ?? 'resend',

        // Resend
        resend_api_key: '', // never echo the secret back
        email_from: settings.email_from ?? '',

        // SMTP
        smtp_host: settings.smtp_host ?? '',
        smtp_port: settings.smtp_port ?? 587,
        smtp_username: settings.smtp_username ?? '',
        smtp_password: '', // never echo the secret back
        smtp_encryption: settings.smtp_encryption ?? 'tls',
        smtp_from_address: settings.smtp_from_address ?? '',
        smtp_from_name: settings.smtp_from_name ?? '',

        // Storage
        storage_driver: settings.storage_driver ?? 'local',
        s3_bucket: settings.s3_bucket ?? '',
        s3_region: settings.s3_region ?? '',
        s3_key: settings.s3_key ?? '',
        s3_secret: '',
        s3_url: settings.s3_url ?? '',

        // Google
        google_client_id: settings.google_client_id ?? '',
        google_client_secret: '',
        google_redirect_url: settings.google_redirect_url ?? '',

        // Stripe (Billing)
        stripe_secret: '',
        stripe_webhook_secret: '',
        stripe_premium_price_id: settings.stripe_premium_price_id ?? '',
        stripe_planner_price_id: settings.stripe_planner_price_id ?? '',
        premium_price: settings.premium_price ?? '',
        planner_price: settings.planner_price ?? '',
    });

    function save(e: React.FormEvent) {
        e.preventDefault();
        form.put('/admin/settings', { preserveScroll: true });
    }

    function uploadLogo(file: File) {
        const fd = new FormData();
        fd.append('logo', file);
        router.post('/admin/settings/logo', fd, { preserveScroll: true, forceFormData: true });
    }

    function removeLogo() {
        router.delete('/admin/settings/logo', { preserveScroll: true });
    }

    function sendTest() {
        if (!testTo) return;
        setTesting(true);
        router.post(
            '/admin/settings/test-email',
            { to: testTo },
            { preserveScroll: true, onFinish: () => setTesting(false) },
        );
    }

    return (
        <AppLayout>
            <div className="max-w-3xl mx-auto px-6 py-10 md:py-14">
                {/* Header */}
                <div className="mb-10">
                    <Link href="/admin" className="text-[12px] text-muted-foreground hover:text-foreground transition tracking-[0.04em] uppercase">
                        ← {t('admin.back')}
                    </Link>
                    <h1 className="font-serif text-[2.4rem] md:text-[3rem] leading-[1.05] text-foreground mt-3">
                        {t('admin.platform_settings')}
                    </h1>
                    <p className="text-[14px] text-muted-foreground mt-2 max-w-lg leading-relaxed">
                        {t('admin.set_subtitle')}
                    </p>
                </div>

                {/* Flash */}
                {flash?.success && (
                    <Banner kind="success">{flash.success}</Banner>
                )}
                {flash?.error && (
                    <Banner kind="error">{flash.error}</Banner>
                )}

                <form onSubmit={save} className="space-y-7">

                    {/* ── Branding (with logo upload) ─────────────────────── */}
                    <Section title={t('admin.set_branding')} subtitle={t('admin.set_branding_sub')}>
                        <Field label={t('admin.set_app_name')}>
                            <input
                                type="text"
                                className="input"
                                value={form.data.app_name}
                                onChange={(e) => form.setData('app_name', e.target.value)}
                            />
                        </Field>

                        <Field label={t('admin.set_base_url')} hint={t('admin.set_base_url_hint')}>
                            <input
                                type="url"
                                className="input"
                                placeholder="https://yourdomain.com"
                                value={form.data.app_base_url}
                                onChange={(e) => form.setData('app_base_url', e.target.value)}
                            />
                        </Field>

                        <Field label={t('admin.set_support_email')}>
                            <input
                                type="email"
                                className="input"
                                value={form.data.support_email}
                                onChange={(e) => form.setData('support_email', e.target.value)}
                            />
                        </Field>

                        {/* Logo upload */}
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-2 tracking-[0.04em] uppercase">
                                {t('admin.set_logo')}
                            </label>
                            <div className="flex items-start gap-5">
                                <div className="relative w-24 h-24 rounded-2xl bg-muted/60 border border-border flex items-center justify-center overflow-hidden flex-shrink-0">
                                    {form.data.app_logo_url ? (
                                        <img
                                            src={form.data.app_logo_url}
                                            alt="Logo"
                                            className="w-full h-full object-contain p-2"
                                        />
                                    ) : (
                                        <span className="font-serif italic text-[1.6rem] text-muted-foreground">
                                            {(form.data.app_name?.[0] ?? 'W').toUpperCase()}
                                        </span>
                                    )}
                                </div>

                                <div className="flex-1">
                                    <div className="flex flex-wrap gap-2">
                                        <button
                                            type="button"
                                            onClick={() => fileInput.current?.click()}
                                            className="bg-foreground text-background px-4 py-2 rounded-[10px] text-[13px] font-medium hover:opacity-90 transition"
                                        >
                                            {t('admin.set_upload_logo')}
                                        </button>
                                        {form.data.app_logo_url && (
                                            <button
                                                type="button"
                                                onClick={removeLogo}
                                                className="border border-border text-foreground px-4 py-2 rounded-[10px] text-[13px] font-medium hover:border-foreground/30 transition"
                                            >
                                                {t('common.remove')}
                                            </button>
                                        )}
                                    </div>
                                    <input
                                        ref={fileInput}
                                        type="file"
                                        accept="image/png,image/jpeg,image/webp,image/svg+xml"
                                        className="hidden"
                                        onChange={(e) => {
                                            const f = e.target.files?.[0];
                                            if (f) uploadLogo(f);
                                            e.target.value = '';
                                        }}
                                    />
                                    <p className="text-[12px] text-muted-foreground mt-2 leading-relaxed">
                                        {t('admin.set_logo_hint')}
                                    </p>
                                </div>
                            </div>

                            {/* Or paste a URL */}
                            <div className="mt-4">
                                <label className="block text-[11.5px] text-muted-foreground mb-1.5">
                                    {t('admin.set_or_paste_url')}
                                </label>
                                <input
                                    type="text"
                                    className="input"
                                    placeholder="https://…/logo.png"
                                    value={form.data.app_logo_url}
                                    onChange={(e) => form.setData('app_logo_url', e.target.value)}
                                />
                            </div>
                        </div>
                    </Section>

                    {/* ── Email delivery ──────────────────────────────────── */}
                    <Section title={t('admin.set_email')} subtitle={t('admin.set_email_sub')}>
                        <Field label={t('admin.set_mail_driver')}>
                            <div className="grid grid-cols-3 gap-2">
                                {(['resend', 'smtp', 'none'] as const).map((d) => (
                                    <button
                                        key={d}
                                        type="button"
                                        onClick={() => form.setData('mail_driver', d)}
                                        className={
                                            form.data.mail_driver === d
                                                ? 'rounded-xl border-2 border-foreground bg-card px-3 py-2.5 text-[13px] font-medium text-foreground transition'
                                                : 'rounded-xl border border-border bg-card px-3 py-2.5 text-[13px] text-muted-foreground hover:border-foreground/30 hover:text-foreground transition'
                                        }
                                    >
                                        {d === 'resend' && t('admin.set_driver_resend')}
                                        {d === 'smtp' && t('admin.set_driver_smtp')}
                                        {d === 'none' && t('admin.set_driver_none')}
                                    </button>
                                ))}
                            </div>
                        </Field>

                        {form.data.mail_driver === 'resend' && (
                            <>
                                <Field label={t('admin.set_resend_key')} hint={t('admin.set_resend_key_hint')}>
                                    <input
                                        type="password"
                                        className="input"
                                        placeholder={settings.resend_api_key ? t('admin.set_secret_set') : 're_…'}
                                        value={form.data.resend_api_key}
                                        onChange={(e) => form.setData('resend_api_key', e.target.value)}
                                        autoComplete="new-password"
                                    />
                                </Field>
                                <Field label={t('admin.set_from_email')}>
                                    <input
                                        type="email"
                                        className="input"
                                        placeholder="noreply@yourdomain.com"
                                        value={form.data.email_from}
                                        onChange={(e) => form.setData('email_from', e.target.value)}
                                    />
                                </Field>
                            </>
                        )}

                        {form.data.mail_driver === 'smtp' && (
                            <>
                                <div className="grid grid-cols-1 md:grid-cols-[1fr_140px] gap-3">
                                    <Field label={t('admin.set_smtp_host')}>
                                        <input
                                            type="text"
                                            className="input"
                                            placeholder="smtp.gmail.com"
                                            value={form.data.smtp_host}
                                            onChange={(e) => form.setData('smtp_host', e.target.value)}
                                        />
                                    </Field>
                                    <Field label={t('admin.set_port')}>
                                        <input
                                            type="number"
                                            className="input"
                                            value={form.data.smtp_port}
                                            onChange={(e) => form.setData('smtp_port', Number(e.target.value))}
                                        />
                                    </Field>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                    <Field label={t('admin.set_username')}>
                                        <input
                                            type="text"
                                            className="input"
                                            autoComplete="off"
                                            value={form.data.smtp_username}
                                            onChange={(e) => form.setData('smtp_username', e.target.value)}
                                        />
                                    </Field>
                                    <Field label={t('admin.set_password')} hint={t('admin.set_keep_blank')}>
                                        <input
                                            type="password"
                                            className="input"
                                            placeholder={settings.smtp_host ? t('admin.set_secret_set') : ''}
                                            autoComplete="new-password"
                                            value={form.data.smtp_password}
                                            onChange={(e) => form.setData('smtp_password', e.target.value)}
                                        />
                                    </Field>
                                </div>

                                <Field label={t('admin.set_encryption')}>
                                    <div className="flex gap-2">
                                        {(['tls', 'ssl'] as const).map((enc) => (
                                            <button
                                                key={enc}
                                                type="button"
                                                onClick={() => form.setData('smtp_encryption', enc)}
                                                className={
                                                    form.data.smtp_encryption === enc
                                                        ? 'flex-1 rounded-xl border-2 border-foreground bg-card px-3 py-2 text-[13px] font-medium text-foreground'
                                                        : 'flex-1 rounded-xl border border-border bg-card px-3 py-2 text-[13px] text-muted-foreground hover:border-foreground/30 hover:text-foreground transition'
                                                }
                                            >
                                                {enc.toUpperCase()}
                                            </button>
                                        ))}
                                    </div>
                                </Field>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                    <Field label={t('admin.set_from_address')}>
                                        <input
                                            type="email"
                                            className="input"
                                            placeholder="noreply@yourdomain.com"
                                            value={form.data.smtp_from_address}
                                            onChange={(e) => form.setData('smtp_from_address', e.target.value)}
                                        />
                                    </Field>
                                    <Field label={t('admin.set_from_name')}>
                                        <input
                                            type="text"
                                            className="input"
                                            placeholder="WedFlow"
                                            value={form.data.smtp_from_name}
                                            onChange={(e) => form.setData('smtp_from_name', e.target.value)}
                                        />
                                    </Field>
                                </div>
                            </>
                        )}

                        {form.data.mail_driver === 'none' && (
                            <p className="text-[13px] text-muted-foreground bg-muted/60 border border-border rounded-xl p-4">
                                {t('admin.set_none_note_1')} <code className="font-mono text-[12px] bg-card px-1.5 py-0.5 rounded">storage/logs</code>{' '}
                                {t('admin.set_none_note_2')}
                            </p>
                        )}

                        {/* Test send */}
                        {form.data.mail_driver !== 'none' && (
                            <div className="border-t border-border pt-5 mt-5">
                                <label className="block text-[12px] font-medium text-muted-foreground mb-2 tracking-[0.04em] uppercase">
                                    {t('admin.set_send_test_label')}
                                </label>
                                <div className="flex flex-col sm:flex-row gap-2">
                                    <input
                                        type="email"
                                        className="input flex-1"
                                        placeholder="you@yourdomain.com"
                                        value={testTo}
                                        onChange={(e) => setTestTo(e.target.value)}
                                    />
                                    <button
                                        type="button"
                                        onClick={sendTest}
                                        disabled={testing || !testTo}
                                        className="bg-foreground text-background px-5 py-2.5 rounded-[10px] text-[13px] font-medium hover:opacity-90 transition disabled:opacity-50 disabled:pointer-events-none"
                                    >
                                        {testing ? t('auth.sending') : t('admin.set_send_test')}
                                    </button>
                                </div>
                                <p className="text-[11.5px] text-muted-foreground mt-2">
                                    {t('admin.set_test_note')}
                                </p>
                            </div>
                        )}
                    </Section>

                    {/* ── Storage ─────────────────────────────────────────── */}
                    <Section title={t('admin.set_storage')} subtitle={t('admin.set_storage_sub')}>
                        <Field label={t('admin.set_storage_driver')}>
                            <div className="flex gap-2">
                                {(['local', 's3'] as const).map((d) => (
                                    <button
                                        key={d}
                                        type="button"
                                        onClick={() => form.setData('storage_driver', d)}
                                        className={
                                            form.data.storage_driver === d
                                                ? 'flex-1 rounded-xl border-2 border-foreground bg-card px-3 py-2.5 text-[13px] font-medium text-foreground'
                                                : 'flex-1 rounded-xl border border-border bg-card px-3 py-2.5 text-[13px] text-muted-foreground hover:border-foreground/30 hover:text-foreground transition'
                                        }
                                    >
                                        {d === 'local' ? t('admin.set_driver_local') : t('admin.set_driver_s3')}
                                    </button>
                                ))}
                            </div>
                        </Field>

                        {form.data.storage_driver === 's3' && (
                            <>
                                <div className="grid grid-cols-2 gap-3">
                                    <Field label={t('admin.set_bucket')}>
                                        <input type="text" className="input" value={form.data.s3_bucket} onChange={(e) => form.setData('s3_bucket', e.target.value)} />
                                    </Field>
                                    <Field label={t('admin.set_region')}>
                                        <input type="text" className="input" value={form.data.s3_region} onChange={(e) => form.setData('s3_region', e.target.value)} />
                                    </Field>
                                </div>
                                <Field label={t('admin.set_access_key')}>
                                    <input type="text" className="input" value={form.data.s3_key} onChange={(e) => form.setData('s3_key', e.target.value)} />
                                </Field>
                                <Field label={t('admin.set_secret')} hint={t('admin.set_keep_blank')}>
                                    <input type="password" className="input" placeholder={settings.s3_bucket ? t('admin.set_secret_set') : ''} value={form.data.s3_secret} onChange={(e) => form.setData('s3_secret', e.target.value)} autoComplete="new-password" />
                                </Field>
                                <Field label={t('admin.set_public_url')}>
                                    <input type="url" className="input" value={form.data.s3_url} onChange={(e) => form.setData('s3_url', e.target.value)} />
                                </Field>
                            </>
                        )}
                    </Section>

                    {/* ── Google OAuth ────────────────────────────────────── */}
                    <Section
                        title={t('admin.set_google')}
                        subtitle={(
                            <>
                                {t('admin.set_google_sub_1')}{' '}
                                <a className="text-primary hover:underline" href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noreferrer">
                                    {t('admin.set_google_console')}
                                </a>{t('admin.set_google_sub_2')}
                            </>
                        )}
                    >
                        <Field label={t('admin.set_client_id')}>
                            <input
                                type="text"
                                className="input"
                                placeholder="123…apps.googleusercontent.com"
                                value={form.data.google_client_id}
                                onChange={(e) => form.setData('google_client_id', e.target.value)}
                            />
                        </Field>
                        <Field label={t('admin.set_client_secret')} hint={t('admin.set_keep_blank')}>
                            <input
                                type="password"
                                className="input"
                                placeholder={settings.google_client_id ? t('admin.set_secret_set') : 'GOCSPX-…'}
                                value={form.data.google_client_secret}
                                onChange={(e) => form.setData('google_client_secret', e.target.value)}
                                autoComplete="new-password"
                            />
                        </Field>
                        <Field label={t('admin.set_redirect_url')} hint={t('admin.set_redirect_hint')}>
                            <input
                                type="url"
                                className="input"
                                placeholder={`${form.data.app_base_url || 'https://yourdomain.com'}/auth/google/callback`}
                                value={form.data.google_redirect_url}
                                onChange={(e) => form.setData('google_redirect_url', e.target.value)}
                            />
                        </Field>
                    </Section>

                    {/* ── Email previews ──────────────────────────────────── */}
                    <Section
                        title={t('admin.set_previews')}
                        subtitle={t('admin.set_previews_sub')}
                    >
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            {EMAIL_PREVIEWS.map((p) => (
                                <div key={p.key} className="border border-border rounded-xl overflow-hidden bg-card">
                                    <iframe
                                        src={`/admin/email-preview/${p.key}`}
                                        title={p.label}
                                        className="w-full h-56 bg-white"
                                        sandbox=""
                                    />
                                    <div className="flex items-center justify-between px-4 py-3 border-t border-border">
                                        <p className="text-[12.5px] font-medium text-foreground">{p.label}</p>
                                        <a
                                            href={`/admin/email-preview/${p.key}`}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="text-[11.5px] text-primary hover:underline"
                                        >
                                            {t('admin.set_open_full')}
                                        </a>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </Section>

                    {/* ── Billing / Stripe ────────────────────────────────── */}
                    <Section
                        title={t('admin.set_billing')}
                        subtitle={(
                            <>
                                {t('admin.set_stripe_sub_1')}{' '}
                                <a className="text-primary hover:underline" href="https://dashboard.stripe.com/apikeys" target="_blank" rel="noreferrer">
                                    {t('admin.set_stripe_dashboard')}
                                </a>{t('admin.set_stripe_sub_2')}
                            </>
                        )}
                    >
                        <Field label={t('admin.set_secret_key')} hint={t('admin.set_keep_blank')}>
                            <input
                                type="password"
                                className="input"
                                placeholder={settings.stripe_premium_price_id || settings.stripe_planner_price_id ? t('admin.set_secret_set') : 'sk_live_… or sk_test_…'}
                                value={form.data.stripe_secret}
                                onChange={(e) => form.setData('stripe_secret', e.target.value)}
                                autoComplete="new-password"
                            />
                        </Field>

                        <Field label={t('admin.set_webhook_secret')} hint={t('admin.set_webhook_hint')}>
                            <input
                                type="password"
                                className="input"
                                placeholder={settings.stripe_premium_price_id || settings.stripe_planner_price_id ? t('admin.set_secret_set') : 'whsec_…'}
                                value={form.data.stripe_webhook_secret}
                                onChange={(e) => form.setData('stripe_webhook_secret', e.target.value)}
                                autoComplete="new-password"
                            />
                        </Field>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <Field label={t('admin.set_premium_price_id')}>
                                <input
                                    type="text"
                                    className="input"
                                    placeholder="price_…"
                                    value={form.data.stripe_premium_price_id}
                                    onChange={(e) => form.setData('stripe_premium_price_id', e.target.value)}
                                />
                            </Field>
                            <Field label={t('admin.set_planner_price_id')}>
                                <input
                                    type="text"
                                    className="input"
                                    placeholder="price_…"
                                    value={form.data.stripe_planner_price_id}
                                    onChange={(e) => form.setData('stripe_planner_price_id', e.target.value)}
                                />
                            </Field>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <Field label={t('admin.set_premium_display')} hint={t('admin.set_premium_display_hint')}>
                                <input
                                    type="text"
                                    className="input"
                                    placeholder="$99"
                                    value={form.data.premium_price}
                                    onChange={(e) => form.setData('premium_price', e.target.value)}
                                />
                            </Field>
                            <Field label={t('admin.set_planner_display')} hint={t('admin.set_planner_display_hint')}>
                                <input
                                    type="text"
                                    className="input"
                                    placeholder="$499"
                                    value={form.data.planner_price}
                                    onChange={(e) => form.setData('planner_price', e.target.value)}
                                />
                            </Field>
                        </div>

                        <p className="text-[12px] text-muted-foreground bg-muted/60 border border-border rounded-xl p-4 leading-relaxed">
                            {t('admin.set_webhook_note_1')}{' '}
                            <code className="font-mono text-[11.5px] bg-card px-1.5 py-0.5 rounded">
                                {form.data.app_base_url || 'https://yourdomain.com'}/billing/webhook
                            </code>
                            <br />
                            {t('admin.set_webhook_note_2')}{' '}
                            <code className="font-mono text-[11.5px] bg-card px-1.5 py-0.5 rounded">checkout.session.completed</code>.
                        </p>
                    </Section>

                    {/* ── Sticky save bar ─────────────────────────────────── */}
                    <div className="sticky bottom-4 z-20">
                        <div className="card-premium px-5 py-4 flex items-center justify-between bg-card/95 backdrop-blur">
                            <p className="text-[12.5px] text-muted-foreground">
                                {t('admin.set_save_note')}
                            </p>
                            <button
                                type="submit"
                                disabled={form.processing}
                                className="bg-foreground text-background px-6 py-2.5 rounded-[10px] text-[13.5px] font-medium hover:opacity-90 transition disabled:opacity-60"
                            >
                                {form.processing ? t('common.saving') : t('admin.set_save')}
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}

/* ─── Building blocks ─────────────────────────────────────────────────────── */

function Section({
    title,
    subtitle,
    children,
}: {
    title: string;
    subtitle?: React.ReactNode;
    children: React.ReactNode;
}) {
    return (
        <section className="card-premium p-7 md:p-8">
            <div className="mb-6">
                <h2 className="font-serif text-[1.45rem] text-foreground leading-tight">{title}</h2>
                {subtitle && (
                    <p className="text-[13px] text-muted-foreground leading-relaxed mt-1.5 max-w-xl">{subtitle}</p>
                )}
            </div>
            <div className="space-y-4">{children}</div>
        </section>
    );
}

function Field({
    label,
    hint,
    children,
}: {
    label: string;
    hint?: string;
    children: React.ReactNode;
}) {
    return (
        <div>
            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5 tracking-[0.04em] uppercase">
                {label}
            </label>
            {children}
            {hint && <p className="text-[11.5px] text-muted-foreground mt-1.5 leading-relaxed">{hint}</p>}
        </div>
    );
}

function Banner({ kind, children }: { kind: 'success' | 'error'; children: React.ReactNode }) {
    const isSuccess = kind === 'success';
    return (
        <div
            className={
                isSuccess
                    ? 'mb-6 px-4 py-3 rounded-xl bg-success-muted border border-success/20 text-success text-[13px]'
                    : 'mb-6 px-4 py-3 rounded-xl bg-danger-muted border border-danger/20 text-danger text-[13px]'
            }
        >
            {children}
        </div>
    );
}
