import { useForm } from "react-hook-form";
import { ActivityRouteEntity } from "../../activity/domain/entities/activity_info_entity";
import { useDataContext } from "../../common/contexts/data_context";
import { useGet } from "../../common/hooks/useGet";
import { GenerateRouteForm } from "./../components/generate_route_form";
import { router } from "expo-router";

export interface GenerateRouteFormValues {
  start: string;
  end: string;
}

export const useGenerateRoute = (townId: number) => {
  const { routeRepository } = useDataContext();
  const { control, handleSubmit } = useForm<GenerateRouteFormValues>({
    defaultValues: {
      start: "",
      end: "",
    },
  });

  const onValidSubmit = async (data: GenerateRouteFormValues) => {
    const { start, end } = data;
    const [startHours] = start.split(":");
    const [endHours] = end.split(":");
    try {
      const route = await routeRepository!.generateRoute(
        townId,
        +startHours,
        +endHours
      );
      router.push(`/routes/generate_route?routeId=${route}`);
    } catch (error) {}
  };

  const onSubmit = async () => {
    await handleSubmit(onValidSubmit, (errors) => {
      console.log(errors);
    })();
  };
  return { control, onSubmit };
};
