import { useEffect, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGlobe, faCopy, faArrowsRotate } from '@fortawesome/pro-duotone-svg-icons';
import { Button } from '@/components/base/buttons/button';
import { TopBar } from '@/components/layout/top-bar';
import {
    WidgetForm,
    emptyWidgetFormValues,
    type WidgetFormValues,
} from '@/components/forms/widget-form';
import { apiClient } from '@/lib/api-client';
import { notify } from '@/lib/toast';

// /settings/widget — Pattern B page for the website widget config. Uses the
// admin endpoint GET /api/config/widget/admin (the plain /api/config/widget
// endpoint returns only the public subset and is used by the embed page).
//
// The site key and site ID are read-only here — generated and rotated by the
// backend. The copy-to-clipboard button on the key helps the admin paste it
// into their website's embed snippet.

type ServerWidgetConfig = {
    enabled: boolean;
    key: string;
    siteId: string;
    url: string;
    allowedOrigins: string[];
    embed: { loginPage: boolean };
    version?: number;
    updatedAt?: string;
};

export const WidgetSettingsPage = () => {
    const [values, setValues] = useState<WidgetFormValues>(emptyWidgetFormValues);
    const [key, setKey] = useState<string>('');
    const [siteId, setSiteId] = useState<string>('');
    const [loading, setLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [isRotating, setIsRotating] = useState(false);

    const loadConfig = async () => {
        try {
            const data = await apiClient.get<ServerWidgetConfig>('/api/config/widget/admin');
            setValues({
                enabled: data.enabled,
                url: data.url ?? '',
                allowedOrigins: data.allowedOrigins ?? [],
                embed: {
                    loginPage: data.embed?.loginPage ?? false,
                },
            });
            setKey(data.key ?? '');
            setSiteId(data.siteId ?? '');
        } catch {
            // toast already shown
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        loadConfig();
    }, []);

    const handleSave = async () => {
        setIsSaving(true);
        try {
            await apiClient.put('/api/config/widget', {
                enabled: values.enabled,
                url: values.url,
                allowedOrigins: values.allowedOrigins,
                embed: values.embed,
            });
            notify.success('Widget updated', 'Changes take effect on next widget load.');
            await loadConfig();
        } catch (err) {
            console.error('[widget] save failed', err);
        } finally {
            setIsSaving(false);
        }
    };

    const handleRotateKey = async () => {
        if (
            !confirm(
                'Rotate the widget key? Any website embed using the old key will stop working until you update it.',
            )
        ) {
            return;
        }
        setIsRotating(true);
        try {
            await apiClient.post('/api/config/widget/rotate-key');
            notify.success('Key rotated', 'Update every embed snippet with the new key.');
            await loadConfig();
        } catch (err) {
            console.error('[widget] rotate failed', err);
        } finally {
            setIsRotating(false);
        }
    };

    const handleCopyKey = async () => {
        try {
            await navigator.clipboard.writeText(key);
            notify.success('Copied', 'Widget key copied to clipboard.');
        } catch {
            notify.error('Copy failed', 'Select the key manually and copy it.');
        }
    };

    return (
        <div className="flex flex-1 flex-col overflow-hidden">
            <TopBar title="Website Widget" subtitle="Configure the chat + booking widget for your hospital website" />

            <div className="flex-1 overflow-y-auto p-6">
                <div className="mx-auto max-w-2xl">
                    <div className="mb-6 flex items-center gap-3 rounded-lg border border-secondary bg-primary p-4">
                        <div className="flex size-10 items-center justify-center rounded-lg bg-brand-secondary">
                            <FontAwesomeIcon icon={faGlobe} className="size-5 text-fg-brand-primary" />
                        </div>
                        <div className="flex-1">
                            <p className="text-sm font-semibold text-primary">One-line embed snippet</p>
                            <p className="text-xs text-tertiary">
                                Drop the script below into your hospital website's <code className="rounded bg-secondary px-1 py-0.5 font-mono">&lt;head&gt;</code> to
                                enable chat and appointment booking. Changing the key requires re-embedding.
                            </p>
                        </div>
                    </div>

                    {loading ? (
                        <div className="flex items-center justify-center py-16">
                            <p className="text-sm text-tertiary">Loading widget settings...</p>
                        </div>
                    ) : (
                        <div className="flex flex-col gap-6">
                            {/* Site key card — read-only with copy + rotate */}
                            <div className="rounded-xl border border-secondary bg-primary p-5 shadow-xs">
                                <div className="mb-3 flex items-center justify-between">
                                    <div>
                                        <h3 className="text-sm font-semibold text-primary">Site key</h3>
                                        <p className="text-xs text-tertiary">
                                            Site ID: <span className="font-mono">{siteId || '—'}</span>
                                        </p>
                                    </div>
                                    <Button
                                        size="sm"
                                        color="tertiary"
                                        iconLeading={({ className }: { className?: string }) => (
                                            <FontAwesomeIcon icon={faArrowsRotate} className={className} />
                                        )}
                                        onClick={handleRotateKey}
                                        isLoading={isRotating}
                                        showTextWhileLoading
                                    >
                                        Rotate
                                    </Button>
                                </div>
                                <div className="flex items-center gap-2">
                                    <code className="flex-1 truncate rounded-lg border border-secondary bg-secondary px-3 py-2 font-mono text-xs text-primary">
                                        {key || '— no key yet —'}
                                    </code>
                                    <Button
                                        size="sm"
                                        color="secondary"
                                        iconLeading={({ className }: { className?: string }) => (
                                            <FontAwesomeIcon icon={faCopy} className={className} />
                                        )}
                                        onClick={handleCopyKey}
                                        isDisabled={!key}
                                    >
                                        Copy
                                    </Button>
                                </div>
                            </div>

                            {/* Editable config */}
                            <div className="rounded-xl border border-secondary bg-primary p-6 shadow-xs">
                                <WidgetForm value={values} onChange={setValues} />

                                <div className="mt-8 flex items-center justify-end border-t border-secondary pt-4">
                                    <Button
                                        size="md"
                                        color="primary"
                                        onClick={handleSave}
                                        isLoading={isSaving}
                                        showTextWhileLoading
                                    >
                                        {isSaving ? 'Saving...' : 'Save changes'}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};
