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

type Field = { k: string; label: string; secret?: boolean; type?: 'text' | 'textarea' | 'select'; options?: string[]; placeholder?: string };

const LABELS: Record<string, string> = {
    paypal: 'PayPal', paystack: 'Paystack', flutterwave: 'Flutterwave',
    razorpay: 'Razorpay', mollie: 'Mollie', offline: 'Bank transfer',
};

const FIELDS: Record<string, Field[]> = {
    paypal: [
        { k: 'mode', label: 'Mode', type: 'select', options: ['live', 'sandbox'] },
        { k: 'client_id', label: 'Client ID' },
        { k: 'secret', label: 'Secret', secret: true },
        { k: 'webhook_id', label: 'Webhook ID', placeholder: 'from PayPal → Webhooks' },
    ],
    paystack: [
        { k: 'secret_key', label: 'Secret key', secret: true, placeholder: 'sk_live_…' },
        { k: 'public_key', label: 'Public key', placeholder: 'pk_live_…' },
    ],
    flutterwave: [
        { k: 'secret_key', label: 'Secret key', secret: true, placeholder: 'FLWSECK-…' },
        { k: 'secret_hash', label: 'Webhook secret hash', secret: true },
    ],
    razorpay: [
        { k: 'key_id', label: 'Key ID', placeholder: 'rzp_live_…' },
        { k: 'key_secret', label: 'Key secret', secret: true },
        { k: 'webhook_secret', label: 'Webhook secret', secret: true },
    ],
    mollie: [
        { k: 'api_key', label: 'API key', secret: true, placeholder: 'live_…' },
    ],
    offline: [
        { k: 'instructions', label: 'Payment instructions (shown to the buyer)', type: 'textarea' },
    ],
};

export default function PaymentGateways({ gateways }: { gateways: any }) {
    const t = useTranslator();
    const origin = typeof window !== 'undefined' ? window.location.origin : '';
    const form = useForm<{ payment_gateways: any }>({ payment_gateways: gateways });
    const gw = form.data.payment_gateways;

    function setField(group: string, key: string, value: any) {
        form.setData('payment_gateways', { ...gw, [group]: { ...gw[group], [key]: value } });
    }
    function save(e: React.FormEvent) {
        e.preventDefault();
        form.put('/admin/settings', { preserveScroll: true });
    }

    return (
        <AppLayout>
            <div className="max-w-3xl mx-auto px-6 py-10">
                <Link href="/admin" className="text-sm text-muted-foreground hover:text-foreground">← {t('admin.back')}</Link>
                <h1 className="font-serif text-3xl mt-2 mb-1">{t('admin.pg_title')}</h1>
                <p className="text-sm text-muted-foreground mb-8 max-w-xl">{t('admin.pg_intro')}</p>

                <form onSubmit={save} className="space-y-5">
                    {/* Shared prices for the non-Stripe gateways */}
                    <section className="bg-card border border-border rounded-xl p-6">
                        <h2 className="font-semibold mb-1">{t('admin.pg_prices')}</h2>
                        <p className="text-xs text-muted-foreground mb-4">{t('admin.pg_prices_help')}</p>
                        <div className="grid grid-cols-3 gap-3">
                            <Field label={t('admin.pg_currency')}>
                                <input className="input" value={gw.prices?.currency ?? 'USD'} onChange={e => setField('prices', 'currency', e.target.value.toUpperCase())} />
                            </Field>
                            <Field label={t('billing.premium')}>
                                <input type="number" step="0.01" className="input" value={gw.prices?.premium ?? ''} onChange={e => setField('prices', 'premium', e.target.value)} />
                            </Field>
                            <Field label={t('billing.planner')}>
                                <input type="number" step="0.01" className="input" value={gw.prices?.planner ?? ''} onChange={e => setField('prices', 'planner', e.target.value)} />
                            </Field>
                        </div>
                    </section>

                    {Object.keys(FIELDS).map(key => {
                        const cfg = gw[key] ?? {};
                        return (
                            <section key={key} className="bg-card border border-border rounded-xl p-6">
                                <label className="flex items-center justify-between mb-4">
                                    <span className="font-semibold">{LABELS[key]}</span>
                                    <span className="inline-flex items-center gap-2 text-sm text-muted-foreground">
                                        {t('admin.pg_enable')}
                                        <input type="checkbox" checked={!!cfg.enabled} onChange={e => setField(key, 'enabled', e.target.checked)} />
                                    </span>
                                </label>
                                <div className="space-y-3">
                                    {FIELDS[key].map(f => (
                                        <Field key={f.k} label={f.label}>
                                            {f.type === 'textarea' ? (
                                                <textarea className="input" rows={3} value={cfg[f.k] ?? ''} onChange={e => setField(key, f.k, e.target.value)} />
                                            ) : f.type === 'select' ? (
                                                <select className="input" value={cfg[f.k] ?? f.options?.[0]} onChange={e => setField(key, f.k, e.target.value)}>
                                                    {f.options?.map(o => <option key={o} value={o}>{o}</option>)}
                                                </select>
                                            ) : (
                                                <input
                                                    type={f.secret ? 'password' : 'text'}
                                                    className="input"
                                                    autoComplete="new-password"
                                                    placeholder={f.secret && cfg[`${f.k}_set`] ? '•••••• (set)' : (f.placeholder ?? '')}
                                                    value={cfg[f.k] ?? ''}
                                                    onChange={e => setField(key, f.k, e.target.value)}
                                                />
                                            )}
                                        </Field>
                                    ))}
                                    {key !== 'offline' && (
                                        <p className="text-[11.5px] text-muted-foreground">
                                            {t('admin.pg_webhook_url')} <code className="font-mono text-[11px] bg-muted px-1.5 py-0.5 rounded">{origin}/billing/webhook/{key}</code>
                                        </p>
                                    )}
                                </div>
                            </section>
                        );
                    })}

                    <div className="sticky bottom-4">
                        <button type="submit" disabled={form.processing} className="bg-primary text-primary-foreground px-6 py-2.5 rounded-lg text-sm shadow-lg disabled:opacity-50">
                            {form.processing ? t('common.saving') : t('admin.set_save')}
                        </button>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
    return (
        <div>
            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">{label}</label>
            {children}
        </div>
    );
}
