"use client"
import CustomSelect from "../../shared/reusableComponents/CustomSelect"
import Bedrooms from "../../icons/Bedrooms"
import Types from "../../icons/Types"
import Size from "../../icons/Size"

import Button from "../../shared/reusableComponents/Reusablebutton"
import Range from "../../icons/Range"
import FilterWrapper from "../components/FilterWrapper"
import { Controller, useForm } from "react-hook-form"
import Category from "../../icons/Category"
import { useQuery } from "@tanstack/react-query"
import apiServiceCall from "@/utils/api/shared/apiServiceCall"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { useSearchParams } from "next/navigation"
import SelectPriceRange from "../../shared/reusableComponents/SelectPriceRange"
import { useTranslations } from "next-intl" // استخدم useTranslations للـ client side

type HomeFilter = {
    size: ""
    type: ""
}

const HomeFilter = ({locale}:{locale:string}) => {
    const t = useTranslations("Header") // استخدم useTranslations للـ client side

    const [categoryOptions, setCategoryOptions] = useState([])
    const [typesOptions, setTypesOptions] = useState([])

    const { data, isSuccess, isLoading } = useQuery({
        queryKey: ["category"],
        queryFn: () => apiServiceCall({ method: "GET", url: "category", headers: {
            lang: locale || "fr",
        }, }),
    })

    const { data: typesData, isSuccess: typeIsSuccess, isLoading:typeIsLoading } = useQuery({
        queryKey: ["types"],
        queryFn: () => apiServiceCall({ method: "GET", url: "type",headers: {
            lang: locale || "fr",
        }, }),
    })

    useEffect(() => {
        
            const options = data?.data?.map((cat: any) => {
                return { value: cat.id, label: cat.name }
            })
            setCategoryOptions(options)
        
     
    }, [isSuccess,data])

    useEffect(() => {
      
        
            const options = typesData?.data?.map((type: any) => {
                return { value: type.id, label: type.name }
            })
            setTypesOptions(options)
        
    }, [ typeIsSuccess, typesData])

    const { register, handleSubmit, watch, control } = useForm()

    const router = useRouter()
    const searchParams = useSearchParams()

    const currentParams = new URLSearchParams(searchParams.toString())

    const handleNavigation = (data: any) => {
        const queryParams = ``
        

        // const types = data?.types?.map((type: { value: string; label: string }) => type.value).join(",")

   
        const types = data?.types?.map((type: { value: string; label: string }) => type?.value).join(",")
          
        if (data?.category_id) {
            if(data?.types){

                data.types = types
            }

            if(data?.min_bedrooms_count){

                data.min_bedrooms_count = data?.min_bedrooms_count.value
            }
            const categoryLabel = data?.category_id?.label

            
            data.category_id = data?.category_id?.value



            if(!data?.types){
                delete data.types
            }
            if(data?.min_price === ""){
                delete data.min_price
            }
            if(data?.max_price=== ""){
                delete data.max_price
            }
            
            if(!data?.min_bedrooms_count){
                delete data.min_bedrooms_count
            }
           
           
            const params = new URLSearchParams(data)
            
            router.push(`/${locale}/property-filter/${categoryLabel}${Object.entries(data)?.length > 0 && `?${params}`}`)
        }

        if (!data?.category_id) {

            if(!data?.types){
                delete data.types
            }
            if(!data?.min_price){
                delete data.min_price
            }
            if(!data?.max_price){
                delete data.min_price
            }
            if(!data?.max_price){
                delete data.min_price
            }
            
            if(!data?.min_bedrooms_count){
                delete data.min_bedrooms_count
            }
            if(!data?.category_id){
                delete data.category_id
            }
            
            const params = new URLSearchParams(data)

            router.push(`/${locale}/property-filter/properites${Object.entries(data)?.length > 0 ? `?${params}`:""}`)
        }

    }

    const onSubmit = (data: any) => {
      
        handleNavigation(data)
    }
    if(typeIsLoading || isLoading){
        return (<>
        <div className='bg-white  z-[999] fixed top-0 bottom-0 w-full left-0 flex h-screen justify-center items-center'>

<div className="loader2"></div>
</div>
        
        </>)
      }
    return (
        <FilterWrapper top="bottom-[15%] translate-y-[15%] lg:bottom-[5%] py-0  lg:translate-y-[5%]  " width="w-full lg:w-[90%] xl:w-[67%] xl:max-w-[1350px] " bg="bg-[#000000A6]">
        <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col lg:flex-row gap-3  w-full">
    <div className="flex flex-col lg:flex-row gap-2 md:gap-5 w-full">
        <div className="w-full relative">
        <div className="absolute bottom-[18%] start-[10px] z-50">
                <Category />
            </div>
            <CustomSelect
                width="100%"
                editOption={null}
                options={categoryOptions}
                styles={{ text: "#FFFFFF", bg: "#FAF9F626" }}
                label={t("category")}
                name="category_id"
                control={control}
                register={register}
                icon={<Category />}
                placeholder={`${t("select")} ${t("category")}`}
            />
        </div>

        <div className="w-full relative">
            <div className="absolute bottom-[22%] start-[10px] z-50">
                <Types />
            </div>

            <CustomSelect
                options={typesOptions}
                styles={{ text: "#FFFFFF", bg: "#FAF9F626" }}
                label={t("property_type")}
                name="types"
                isMulti
                control={control}
                register={register}
                placeholder={t("property_type_placeholder")}
            />
        </div>

        <div className="w-full relative">
        <div className="absolute bottom-[22%] start-[10px] z-50">
                <Bedrooms />
            </div>
            <CustomSelect
                width="100%"
                options={[
                    { value: "1", label:  `1 ${t("bedrooms")}` },
                    { value: "2", label: `2 ${t("bedrooms")}` },
                    { value: "3", label: `3 ${t("bedrooms")}` },
                    { value: "4", label: `4 ${t("bedrooms")}` },
                    { value: "5", label: `5 ${t("bedrooms")}`}
                ]}
                editOption={null}
                placeholder={`${t("select")} ${t("bedrooms")}`}
                styles={{ text: "#FFFFFF", bg: "#FAF9F626" }}
                icon={<Bedrooms />}
                label={t("bedrooms")}
                name="min_bedrooms_count"
                control={control}
                register={register}
            />
        </div>

        <div className="w-full">
            <SelectPriceRange
                label={t("price")}
                className="!bg-[#FAF9F626] backdrop-blur-[1px] text-white"
                name={{ min: 'min_price', max: 'max_price' }}
                formInputs={{ register: register, watch: watch }}
            />
        </div>
    </div>

    <div className="flex w items-end">
        <Button styleMe type="submit">{t("view_properties")}</Button>
    </div>
</form>

        </FilterWrapper>
    )
}

export default HomeFilter