"use client";
import React, {SetStateAction} from "react";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
import {useRouter, useSearchParams} from "next/navigation";
import {API_URL} from "@/constants";
import Loader from "./Loader";

interface Data {
  id: number;
  slug: string;
  title:string
}
async function fetchData() {
  const res = await fetch(`${API_URL}/language/get/all`, {
    cache: "no-store",
    credentials: "include",
  });

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  const data = await res.json();
  return data;
}

export default function LanguagesFilterBox({
  lang,
  setLang,
}: {
  lang: string;
  setLang: React.Dispatch<SetStateAction<string>>;
}) {
  const urlSearchParams = useSearchParams();
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(false);

  const searchParams = new URLSearchParams(urlSearchParams);
  const router = useRouter();

  React.useEffect(() => {
    let active = true;

    setLoading(true);
    fetchData()
      .then((res) => {
        if (!active) return;
        console.log(res.data)
        setData(res.data);
      })
      .catch(console.error)
      .finally(() => active && setLoading(false));

    return () => {
      active = false;
    };
  }, []);

  if (loading) {
    return (
      <div className="text-sm text-muted-foreground">
        <Loader />
      </div>
    );
  }
  return (
    <>
      <Select onValueChange={(value) => setLang(value)}>
        <SelectTrigger className="w-[180px] bg-white" dir="rtl">
          <SelectValue placeholder="زبان انتخاب کنید" />
        </SelectTrigger>
        <SelectContent>
          <SelectGroup>
            {data?.map((item: Data) => (
              <SelectItem key={item.id} value={item.slug}>
                {item.title}
              </SelectItem>
            ))}
          </SelectGroup>
        </SelectContent>
      </Select>
    </>
  );
}
