import type { Route } from "./+types/dishes.$id.edit";
import { useCallback, useEffect, useState } from "react";
import PageTitle from "~/components/ui/PageTitle";
import EditDishForm from "~/components/features/dishes/EditDishForm";
import { DishType } from "~/types/DishType";
import Spinner from "~/components/Spinner";
import { fetchDish } from "~/utils/api/dishApi";
import SyncUsersForm from "~/components/features/dishes/SyncUsersForm";
import { ChevronLeftIcon } from "@heroicons/react/16/solid";
import useRoutes from "~/hooks/useRoutes";
import OutlineLinkButton from "~/components/ui/Buttons/OutlineLinkButton";
import Hr from "~/components/ui/Hr";
import { useParams } from "react-router";

export function meta({}: Route.MetaArgs) {
  return [
    { title: "Dish Planner - Edit Dish" },
    { name: "description", content: "Edit dish details" },
  ];
}

export default function EditDishPage() {
  const params = useParams();
  const id = Number(params.id);
  const [dish, setDish] = useState<DishType | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const routes = useRoutes();

  const loadDish = useCallback(async () => {
    try {
      const fetchedDish = await fetchDish(id);
      setDish(fetchedDish);
    } catch (error) {
      console.error("Error fetching dish:", error);
      throw new Error("No token found in localStorage.");
    } finally {
      setIsLoading(false);
    }
  }, [id]);

  useEffect(() => {
    loadDish();
  }, [loadDish]);

  if (isLoading || dish === null) {
    return <Spinner />;
  }

  return (
    <div>
      <div className="flex mb-3">
        <PageTitle>Edit Dish</PageTitle>
        <OutlineLinkButton href={routes.dish.index()}>
          <ChevronLeftIcon className="w-5 h-5 mr-1" />
          <p className="text-sm">BACK</p>
        </OutlineLinkButton>
      </div>

      <EditDishForm dish={dish} />

      <Hr className="mt-8" />

      <SyncUsersForm dish={dish} reloadDish={loadDish} />
    </div>
  );
}
