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

type Field = { set: boolean; is_secret: boolean; value: string | null };
type Groups = Record<string, Record<string, Field>>;

const LABELS: Record<string, string> = {
    salesforce: 'Salesforce', google_ads: 'Google Ads', meta_ads: 'Meta Ads',
    quickbooks: 'QuickBooks', ai: 'AI Analyst (Anthropic)',
};

export default function Credentials() {
    const { groups } = usePage().props as unknown as { groups: Groups };
    const [edits, setEdits] = useState<Record<string, Record<string, string>>>({});

    const setVal = (group: string, key: string, val: string) =>
        setEdits((e) => ({ ...e, [group]: { ...e[group], [key]: val } }));

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

    return (
        <>
            <Head title="Provider Credentials" />
            <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" /> Provider Credentials
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        Manage OAuth app keys and API keys. Secrets are encrypted at rest and never shown after saving.
                    </p>
                </header>

                <div className="space-y-4">
                    {Object.entries(groups).map(([group, fields]) => (
                        <section key={group} className="rounded-xl border border-border bg-card p-5">
                            <h2 className="mb-3 font-medium text-foreground">{LABELS[group] ?? group}</h2>
                            <div className="space-y-3">
                                {Object.entries(fields).map(([key, field]) => (
                                    <div key={key}>
                                        <label className="mb-1 flex items-center gap-2 text-sm font-medium text-foreground capitalize">
                                            {key.replace(/_/g, ' ')}
                                            {field.set && <span className="inline-flex items-center gap-0.5 text-[11px] text-emerald-600"><Check className="size-3" /> set</span>}
                                        </label>
                                        <input
                                            type={field.is_secret ? 'password' : 'text'}
                                            defaultValue={field.value ?? ''}
                                            placeholder={field.set ? '•••••••• (leave blank to keep)' : 'Not set'}
                                            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>
                                ))}
                                <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 {LABELS[group] ?? group}
                                </button>
                            </div>
                        </section>
                    ))}
                </div>
            </div>
        </>
    );
}
