import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus, faTrash } from '@fortawesome/pro-duotone-svg-icons';
import { Input } from '@/components/base/input/input';
import { Toggle } from '@/components/base/toggle/toggle';
import { Button } from '@/components/base/buttons/button';

// Widget form — mirrors WidgetConfig from
// helix-engage-server/src/config/widget.defaults.ts. The site key and site ID
// are read-only (generated / rotated by the backend), the rest are editable.
//
// allowedOrigins is an origin allowlist — an empty list means "any origin"
// which is useful for testing but should be tightened in production.

export type WidgetFormValues = {
    enabled: boolean;
    url: string;
    allowedOrigins: string[];
    embed: {
        loginPage: boolean;
    };
};

export const emptyWidgetFormValues = (): WidgetFormValues => ({
    enabled: true,
    url: '',
    allowedOrigins: [],
    embed: {
        loginPage: false,
    },
});

type WidgetFormProps = {
    value: WidgetFormValues;
    onChange: (value: WidgetFormValues) => void;
};

export const WidgetForm = ({ value, onChange }: WidgetFormProps) => {
    const [originDraft, setOriginDraft] = useState('');

    const addOrigin = () => {
        const trimmed = originDraft.trim();
        if (!trimmed) return;
        if (value.allowedOrigins.includes(trimmed)) {
            setOriginDraft('');
            return;
        }
        onChange({ ...value, allowedOrigins: [...value.allowedOrigins, trimmed] });
        setOriginDraft('');
    };

    const removeOrigin = (origin: string) => {
        onChange({ ...value, allowedOrigins: value.allowedOrigins.filter((o) => o !== origin) });
    };

    return (
        <div className="flex flex-col gap-8">
            <section className="flex flex-col gap-4">
                <div>
                    <h3 className="text-sm font-semibold text-primary">Activation</h3>
                    <p className="mt-1 text-xs text-tertiary">
                        When disabled, widget.js returns an empty response and the script no-ops on the
                        embedding page. Use this as a kill switch if something goes wrong in production.
                    </p>
                </div>
                <div className="rounded-lg border border-secondary bg-secondary p-4">
                    <Toggle
                        label="Website widget enabled"
                        isSelected={value.enabled}
                        onChange={(checked) => onChange({ ...value, enabled: checked })}
                    />
                </div>
            </section>

            <section className="flex flex-col gap-4">
                <div>
                    <h3 className="text-sm font-semibold text-primary">Hosting</h3>
                    <p className="mt-1 text-xs text-tertiary">
                        Public base URL where widget.js is served from. Leave blank to use the same origin as
                        this sidecar (the common case).
                    </p>
                </div>
                <Input
                    label="Public URL"
                    placeholder="https://widget.hospital.com"
                    value={value.url}
                    onChange={(v) => onChange({ ...value, url: v })}
                />
            </section>

            <section className="flex flex-col gap-4">
                <div>
                    <h3 className="text-sm font-semibold text-primary">Allowed origins</h3>
                    <p className="mt-1 text-xs text-tertiary">
                        Origins where the widget may be embedded. An empty list means any origin is accepted
                        (test mode). In production, list every hospital website + staging environment
                        explicitly.
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    <div className="flex-1">
                        <Input
                            placeholder="https://hospital.com"
                            value={originDraft}
                            onChange={setOriginDraft}
                        />
                    </div>
                    <Button
                        size="sm"
                        color="secondary"
                        iconLeading={({ className }: { className?: string }) => (
                            <FontAwesomeIcon icon={faPlus} className={className} />
                        )}
                        onClick={addOrigin}
                        isDisabled={!originDraft.trim()}
                    >
                        Add
                    </Button>
                </div>
                {value.allowedOrigins.length === 0 ? (
                    <p className="rounded-lg border border-dashed border-secondary bg-secondary p-4 text-center text-xs text-tertiary">
                        Any origin allowed — widget runs in test mode.
                    </p>
                ) : (
                    <ul className="flex flex-col gap-2 rounded-lg border border-secondary bg-secondary p-3">
                        {value.allowedOrigins.map((origin) => (
                            <li
                                key={origin}
                                className="flex items-center justify-between rounded-md bg-primary px-3 py-2 text-sm"
                            >
                                <span className="font-mono text-primary">{origin}</span>
                                <button
                                    type="button"
                                    onClick={() => removeOrigin(origin)}
                                    className="flex size-6 items-center justify-center rounded-md text-fg-quaternary hover:bg-secondary_hover hover:text-fg-error-primary"
                                    title="Remove origin"
                                >
                                    <FontAwesomeIcon icon={faTrash} className="size-3" />
                                </button>
                            </li>
                        ))}
                    </ul>
                )}
            </section>

            <section className="flex flex-col gap-4">
                <div>
                    <h3 className="text-sm font-semibold text-primary">Embed surfaces</h3>
                    <p className="mt-1 text-xs text-tertiary">
                        Where inside this application the widget should auto-render. Keep these off if you
                        only plan to embed it on your public hospital website.
                    </p>
                </div>
                <div className="rounded-lg border border-secondary bg-secondary p-4">
                    <Toggle
                        label="Show on staff login page"
                        hint="Useful for smoke-testing without a public landing page."
                        isSelected={value.embed.loginPage}
                        onChange={(checked) =>
                            onChange({ ...value, embed: { ...value.embed, loginPage: checked } })
                        }
                    />
                </div>
            </section>
        </div>
    );
};
