import { useEffect, useRef, useState } from "react";
import {
    ActionIcon,
    Box,
    CheckIcon,
    Combobox,
    Flex,
    Group,
    ScrollArea,
    Text,
    useCombobox,
} from "@mantine/core";
import style from "@/components/ui/PhoneInput/PhoneInput.module.css";
import { Country } from "@/components/ui/PhoneInput/types";
import countryOptionsDataMap from "@/components/ui/PhoneInput/utils/countryOptionsDataMap";


const countryOptionsData = Object.values(countryOptionsDataMap);

type Props = {
    country: Country;
    setCountry: (country: Country) => void;
    disabled: boolean | undefined;
    leftSectionWidth: number;
    inputWidth?: number;
};

const CountrySelect = ({
    country,
    setCountry,
    disabled,
    leftSectionWidth,
    inputWidth,
}: Props) => {
    const [search, setSearch] = useState("");

    const selectedRef = useRef<HTMLDivElement>(null);

    const combobox = useCombobox({
        onDropdownClose: () => {
            combobox.resetSelectedOption();
            setSearch("");
        },

        onDropdownOpen: () => {
            combobox.focusSearchInput();
            setTimeout(() => {
                selectedRef.current?.scrollIntoView({
                    behavior: "instant",
                    block: "center",
                });
            }, 0);
        },
    });

    const options = countryOptionsData
        .filter(item =>
            item.name.toLowerCase().includes(search.toLowerCase().trim())
        )
        .map(item => (
            <Combobox.Option
                ref={item.code === country.code ? selectedRef : undefined}
                value={item.code}
                key={item.code}>
                <Group
                    justify={"space-between"}
                    wrap={"nowrap"}
                    align={"center"}>
                    <Text>
                        {item.emoji} +{item.callingCode} | {item.name}
                    </Text>
                    {item.code === country.code && (
                        <Box>
                            <CheckIcon size={14} />
                        </Box>
                    )}
                </Group>
            </Combobox.Option>
        ));

    useEffect(() => {
        if (search) {
            combobox.selectFirstOption();
        }
    }, [search]);

    return (
        <Combobox
            store={combobox}
            position={"bottom-start"}
            transitionProps={{ duration: 200, transition: "fade-down" }}
            styles={{
                dropdown: {
                    borderRadius: "15px",
                    minWidth: `${inputWidth}px`,
                },
            }}
            onOptionSubmit={val => {
                setCountry(countryOptionsDataMap[val]);
                combobox.closeDropdown();
            }}>
            <Combobox.Target withAriaAttributes={false}>
                <ActionIcon
                    variant={"transparent"}
                    onClick={() => combobox.toggleDropdown()}
                    size={"lg"}
                    tabIndex={-1}
                    disabled={disabled}
                    w={leftSectionWidth}>
                    <Flex
                        align={"center"}
                        ml={15}
                        w={"100%"}
                        className={style["country-select"]}>
                        <span>
                            {country.emoji} +{country.callingCode}
                        </span>
                    </Flex>
                </ActionIcon>
            </Combobox.Target>

            <Combobox.Dropdown>
                <Combobox.Search
                    value={search}
                    onChange={event => setSearch(event.currentTarget.value)}
                    placeholder="Поиск..."
                    className={style["country-search"]}
                    size={"md"}
                />
                <Combobox.Options>
                    <ScrollArea.Autosize
                        mah={250}
                        type="scroll">
                        {options.length > 0 ? (
                            options
                        ) : (
                            <Combobox.Empty>Нет данных</Combobox.Empty>
                        )}
                    </ScrollArea.Autosize>
                </Combobox.Options>
            </Combobox.Dropdown>
        </Combobox>
    );
};

export default CountrySelect;
