"use client";
import React 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;
  translations: {
    id: number;
    displayName: string;
    lang: string;
  }[];
}
async function fetchData() {
  console.log('filters box')
  const res = await fetch(`${API_URL}/expertise/fa/get/all/list?lang=fa`, {
    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 ExpertiseFilterBox() {
  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;
        setData(res.data);
      })
      .catch(console.error)
      .finally(() => active && setLoading(false));

    return () => {
      active = false;
    };
  }, []);
  const handleFilter = (value: string) => {
    searchParams.set("e", value);
    router.push(`/doctors${searchParams ? `?${searchParams.toString()}` : ""}`);
  };

  if (loading) {
    return (
      <div className="text-sm text-muted-foreground">
        <Loader />
      </div>
    );
  }
  return (
    <>
      <Select onValueChange={handleFilter}>
        <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.translations[0].displayName}
              </SelectItem>
            ))}
          </SelectGroup>
        </SelectContent>
      </Select>
    </>
  );
}
