import { randomTask } from "@/api/fetcher";
import { getHeaderTitle } from "@react-navigation/elements";
import type { NativeStackHeaderProps } from "@react-navigation/native-stack";
import { router, useGlobalSearchParams } from "expo-router";
import { Appbar } from "react-native-paper";

export default function ListNavigationBar({
  options,
  route,
}: NativeStackHeaderProps) {
  const { listId, listName } = useGlobalSearchParams<{
    listId: string;
    listName?: string;
  }>();
  const title = getHeaderTitle(options, listName || route.name);
  const back = router.canGoBack();

  return (
    <Appbar.Header elevated>
      {back || (route.path !== "/") ? (
        <Appbar.BackAction
          onPress={() => (back ? router.back() : router.replace("/"))}
        />
      ) : null}
      <Appbar.Content title={title} />
      <Appbar.Action
        icon="dice-multiple-outline"
        onPress={() =>
          randomTask(listId || null).then((data) =>
            router.push({
              pathname: "/tasks/[taskId]",
              params: { taskId: data.id, taskName: data.name },
            })
          )
        }
      />
      {/*<Appbar.Action icon="magnify" onPress={() => {}} />*/}
    </Appbar.Header>
  );
}
