import { Select, Spin } from "antd";
import { observer } from "mobx-react";
import { useEffect, useMemo, useState } from "react";

import { useStores } from "../../../store/stores.js";
import { __ } from "../../../utils/i18n.js";

import type { FC } from "react";

const ConsentRefererSelect: FC<{ value?: string; onChange?: (url: string) => void }> = observer(
    ({ value, onChange }) => {
        const [selected, setSelected] = useState(value);
        const [focusedOnce, setFocusedOnce] = useState(false);
        const { consentStore } = useStores();
        const { busyReferer, referer } = consentStore;

        useEffect(() => {
            if (focusedOnce) {
                consentStore.fetchReferer();
            }
        }, [focusedOnce]);

        const options = useMemo(() => {
            const groupedOptions = referer.reduce(
                (acc, url) => {
                    try {
                        const { hostname, origin } = new URL(url);
                        if (!acc[hostname]) {
                            acc[hostname] = [];
                        }
                        acc[hostname].push({ label: url.substring(origin.length), value: url });
                    } catch (e) {
                        // ignore
                    }
                    return acc;
                },
                {} as Record<string, { label: string; value: string }[]>,
            );

            return Object.entries(groupedOptions).map(([hostname, urls]) => ({
                label: hostname,
                options: urls.sort((a, b) => a.label.localeCompare(b.label)),
            }));
        }, [referer]);

        return (
            <Select
                showSearch
                onFocus={() => setFocusedOnce(true)}
                value={selected}
                notFoundContent={busyReferer ? <Spin size="small" /> : null}
                loading={busyReferer}
                allowClear
                onClear={() => {
                    setSelected(undefined);
                    onChange?.(undefined);
                }}
                dropdownAlign={{ points: ["tr", "br"] }}
                dropdownStyle={{ width: 500 }}
                style={{ width: 200 }}
                placeholder={__("Filter by URL...")}
                onChange={(value: string) => {
                    const useValue = value || undefined;
                    setSelected(useValue);
                    onChange?.(useValue);
                }}
                options={options}
            />
        );
    },
);

export { ConsentRefererSelect };
