"use client"

import { useState, useEffect, useRef } from "react"
import { useEstablishmentStore } from "@/shared/api/stores/admin-service/establishmentStore"
import { useEstablishmentSearch } from "./use-establishment-search"

interface EstablishmentOption {
    value: string
    label: string
}

export const useEstablishmentOptions = () => {
    const { establishmentNamesAndIds, searchWithSpecificInfo } = useEstablishmentStore()
    const { searchEstablishments, isLoading } = useEstablishmentSearch()

    const [establishmentOptions, setEstablishmentOptions] = useState<EstablishmentOption[]>([])
    const singleResultRef = useRef<EstablishmentOption[]>([])

    useEffect(() => {
        const fetchData = async () => {
            await searchWithSpecificInfo()
        }

        fetchData()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    useEffect(() => {
        if (establishmentNamesAndIds.length > 0) {
            const newOptions = establishmentNamesAndIds.map((establishment) => ({
                value: establishment.id.toString(),
                label: establishment.name,
            }))

            if (establishmentNamesAndIds.length === 1) {
                const existingIds = singleResultRef.current.map((opt) => opt.value)
                const newUniqueOptions = newOptions.filter((newOpt) => !existingIds.includes(newOpt.value))

                if (newUniqueOptions.length > 0) {
                    singleResultRef.current = [...singleResultRef.current, ...newUniqueOptions]
                }

                setEstablishmentOptions(singleResultRef.current)
            } else {
                const combinedOptions = [...newOptions, ...singleResultRef.current]

                const uniqueOptions = combinedOptions.reduce((acc, current) => {
                    const exists = acc.find((item) => item.value === current.value)
                    if (!exists) {
                        acc.push(current)
                    }
                    return acc
                }, [] as EstablishmentOption[])

                setEstablishmentOptions(uniqueOptions)
            }
        }
    }, [establishmentNamesAndIds])

    return {
        searchEstablishments,
        isLoading,
        establishmentOptions,
    }
}
