import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { KeyRound, Check, Save, Plug, Loader2, CircleCheck, CircleX, Copy } from 'lucide-react';

type Field = { label: string; placeholder: string; is_secret: boolean; set: boolean; value: string | null };
type Groups = Record<string, Record<string, Field>>;
type TestState = { loading: boolean; ok?: boolean; message?: string };

const TITLES: Record<string, string> = {
    ai: 'AI Analyst (Anthropic)', mail: 'Email / SMTP', salesforce: 'Salesforce',
    google_ads: 'Google Ads', ga4: 'Google Analytics 4', meta_ads: 'Meta Ads', quickbooks: 'QuickBooks',
};

const HINTS: Record<string, string> = {
    ai: 'Get a key at console.anthropic.com. Enables the AI Analyst.',
    mail: 'Any SMTP provider works (cPanel mailbox, Brevo, Postmark…). Fill in From address too — it appears as the sender on invitations and reports.',
    salesforce: 'Setup → App Manager → New Connected App. Enable OAuth, PKCE, and scopes: api refresh_token offline_access.',
    google_ads: 'Google Cloud console OAuth client + an approved Developer Token.',
    ga4: 'Google Cloud OAuth client with the Analytics Data API enabled. Property ID is the numeric GA4 property.',
    meta_ads: 'developers.facebook.com app with ads_read permission.',
    quickbooks: 'developer.intuit.com app. Sandbox and production use different keys.',
};

export default function Credentials() {
    const props = usePage().props as unknown as {
        groups: Groups; redirectUris: Record<string, string>;
        auth?: { user?: { email?: string } };
    };
    const { groups, redirectUris } = props;

    const [edits, setEdits] = useState<Record<string, Record<string, string>>>({});
    const [tests, setTests] = useState<Record<string, TestState>>({});
    // Default the test recipient to the signed-in admin's own address.
    const [testTo, setTestTo] = useState(props.auth?.user?.email ?? '');

    const setVal = (g: string, k: string, v: string) =>
        setEdits((e) => ({ ...e, [g]: { ...e[g], [k]: v } }));

    const save = (g: string) =>
        router.post('/admin/settings/credentials', { group: g, values: edits[g] ?? {} }, {
            preserveScroll: true, onSuccess: () => setEdits((e) => ({ ...e, [g]: {} })),
        });

    const test = async (g: string) => {
        setTests((t) => ({ ...t, [g]: { loading: true } }));
        try {
            const res = await fetch('/admin/settings/credentials/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name=csrf-token]') as HTMLMetaElement)?.content ?? '',
                    'X-Requested-With': 'XMLHttpRequest',
                },
                body: JSON.stringify({ group: g, to: g === 'mail' ? testTo : undefined }),
            });
            const d = await res.json();
            setTests((t) => ({ ...t, [g]: { loading: false, ok: d.ok, message: d.message } }));
        } catch {
            setTests((t) => ({ ...t, [g]: { loading: false, ok: false, message: 'Test request failed.' } }));
        }
    };

    return (
        <>
            <Head title="Integration Settings" />
            <div className="mx-auto w-full max-w-3xl px-6 py-8">
                <header className="mb-6">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <KeyRound className="size-5 text-primary" /> Integration Settings
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        Enter provider keys and test each connection. Secrets are encrypted and never shown again after saving.
                    </p>
                </header>

                <div className="space-y-4">
                    {Object.entries(groups).map(([group, fields]) => {
                        const t = tests[group];
                        const isMail = group === 'mail';

                        return (
                            <section key={group} className="rounded-xl border border-border bg-card p-5">
                                <div className="mb-1 flex items-center justify-between gap-3">
                                    <h2 className="font-medium text-foreground">{TITLES[group] ?? group}</h2>
                                    <div className="flex items-center gap-2">
                                        {isMail && (
                                            <input
                                                type="email" value={testTo}
                                                onChange={(e) => setTestTo(e.target.value)}
                                                placeholder="send test to…"
                                                className="w-56 rounded-md border border-border bg-background px-2.5 py-1.5 text-xs" />
                                        )}
                                        <button onClick={() => test(group)} disabled={t?.loading || (isMail && !testTo)}
                                            className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium hover:bg-muted disabled:opacity-50">
                                            {t?.loading ? <Loader2 className="size-3.5 animate-spin" /> : <Plug className="size-3.5" />}
                                            {isMail ? 'Send test email' : 'Test connection'}
                                        </button>
                                    </div>
                                </div>
                                {HINTS[group] && <p className="mb-3 text-xs text-muted-foreground">{HINTS[group]}</p>}

                                {redirectUris[group] && (
                                    <div className="mb-3 flex items-center gap-2 rounded-md bg-muted/50 px-3 py-2">
                                        <span className="text-[11px] text-muted-foreground">Redirect URI:</span>
                                        <code className="flex-1 truncate text-[11px] text-foreground">{redirectUris[group]}</code>
                                        <button onClick={() => navigator.clipboard.writeText(redirectUris[group])}
                                            className="text-muted-foreground hover:text-foreground"><Copy className="size-3.5" /></button>
                                    </div>
                                )}

                                <div className="space-y-3">
                                    {Object.entries(fields).map(([key, f]) => (
                                        <div key={key}>
                                            <label className="mb-1 flex items-center gap-2 text-sm font-medium text-foreground">
                                                {f.label}
                                                {f.set && <span className="inline-flex items-center gap-0.5 text-[11px] text-emerald-600"><Check className="size-3" /> set</span>}
                                            </label>
                                            <input
                                                type={f.is_secret ? 'password' : 'text'}
                                                defaultValue={f.value ?? ''}
                                                placeholder={f.set && f.is_secret ? '•••••••• (blank = keep current)' : f.placeholder}
                                                onChange={(e) => setVal(group, key, e.target.value)}
                                                className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />
                                        </div>
                                    ))}
                                </div>

                                <div className="mt-4 flex flex-wrap items-center gap-3">
                                    <button onClick={() => save(group)}
                                        className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3.5 py-2 text-sm font-medium text-primary-foreground hover:opacity-90">
                                        <Save className="size-4" /> Save
                                    </button>
                                    {t && !t.loading && t.message && (
                                        <span className={`inline-flex items-center gap-1.5 text-xs ${t.ok ? 'text-emerald-600' : 'text-destructive'}`}>
                                            {t.ok ? <CircleCheck className="size-4" /> : <CircleX className="size-4" />}
                                            {t.message}
                                        </span>
                                    )}
                                </div>
                            </section>
                        );
                    })}
                </div>
            </div>
        </>
    );
}
