import { useEffect, useState } from "react";
import { isApiError, type ApiError } from "../types/api/error";
import { DeleteRecipe, GetRecipe, IsRecipeOwner } from "../services/RecipeService";
import type { Recipe } from "../types/recipe";
import { useNavigate, useParams } from "react-router-dom";

import RecipePlaceholder from "../assets/images/recipe_placeholder_wide.jpg"
import RecipeMetaData from "../components/display/RecipeMetaData";
import MadeButton from "../components/buttons/MadeButton";
import ShareButton from "../components/buttons/ShareButton";
import FavoriteButton from "../components/buttons/FavoriteButton";
import TagList from "../components/items/TagList";
import IngredientList from "../components/items/IngredientList";
import InstructionList from "../components/items/InstructionList";
import Spinner from "../components/Spinner";
import { GetUser } from "../services/UserService";
import type { User } from "../types/user";
import DeleteButton from "../components/buttons/DeleteButton";
import ROUTE_CONSTANTS from "../types/routes";
import ConfirmRecipeDeleteModal from "../components/modals/ConfirmRecipeDeleteModal";
import EditButton from "../components/buttons/EditButton";

export default function RecipePage() {
  // Url params
  const { id } = useParams();

  // Page state
  const [recipe, setRecipe] = useState<Recipe | null>(null);
  const [author, setAuthor] = useState<User | null>(null);
  const [error, setError] = useState<string>("");

  const [isAuthor, setIsAuthor] = useState<boolean>(false);
  const [isDeleting, setIsDeleting] = useState<boolean>(false);

  const navigate = useNavigate();

  // Functions
  const getRecipe = async (id: number) => {
    const result: Recipe | ApiError = await GetRecipe(id);
    if (isApiError(result)) {
      setError(result.message);
    } else {
      setRecipe(result);
    }
  }

  const getAuthor = async (id: number) => {
    const result: User | ApiError = await GetUser(id);
    if (isApiError(result)) {
      setError(result.message);
    } else {
      setAuthor(result);
    }
  }

  const getIsAuthor = async () => {
    if (!recipe) return;
    const response = await IsRecipeOwner(recipe.Id);
    if (isApiError(response)) {
      setError(response.message);
      return;
    }
    setIsAuthor(response);
  }

  const deleteRecipe = async (id: number) => {
    const error = await DeleteRecipe(id);
    if (isApiError(error)) {
      setError(error.message)
      return;
    }

    // TODO: Some toast, maybe?

    await navigate(ROUTE_CONSTANTS.Home);
  }

  // Handlers
  const deleteHandler = () => {
    if (!recipe || !isAuthor) return;
    setIsDeleting(true);
  }

  const editHandler = () => {
    if (!recipe || !isAuthor) return;
    const route = ROUTE_CONSTANTS.Edit(Number(recipe.Id));
    void navigate(route);
  }

  // Effects
  useEffect(() => {
    void getRecipe(Number(id));
  }, [id]);

  useEffect(() => {
    if (recipe)
      void getAuthor(recipe.UserId);
  }, [recipe]);

  useEffect(() => {
    void getIsAuthor();
  }, [recipe, author]);

  // BUG: Prob remove
  useEffect(() => {
    if (error)
      console.error(error);
  }, [error]);

  return recipe ? (
    <>
      {isDeleting &&
        <ConfirmRecipeDeleteModal
          cancelHandler={() => setIsDeleting(false)}
          deleteHandler={() => void deleteRecipe(recipe.Id)}
        />}

      <img className="bg-gray-100 w-full h-64 md:h-96 mx-auto mb-8" src={RecipePlaceholder} />
      <div className="px-4 py-8 md:px-8">
        <h1 className="text-3xl md:text-4xl font-bold text-gray-800">{recipe.Title}</h1>
        <p className="text-sm mt-2 mb-1 text-gray-700">{author ? author.Name : "Loading..."}</p>
        <p className="text-sm mb-2 text-gray-700">Category: {recipe.Category}</p>
      </div>
      <RecipeMetaData recipe={recipe} />
      <section className="w-full flex flex-col md:flex-row gap-x-4 gap-y-2 py-8 px-4 md:px-8 flex-wrap">
        <FavoriteButton favorite={recipe.Favorite} id={recipe.Id} />
        <MadeButton id={recipe.Id} />
        <ShareButton id={recipe.Id} />

        {isAuthor && (
          <>
            <DeleteButton clickHandler={deleteHandler} />
            <EditButton clickHandler={editHandler} />
          </>
        )}
      </section>
      <div className="px-4 py-8 md:px-8">
        <h3 className="text-xl text-gray-800 font-semibold mb-2">About this recipe</h3>
        <p className="text-gray-700 whitespace-pre-line wrap-break-word">{recipe.Description}</p>
      </div>
      <IngredientList sections={recipe.Sections} ingredients={recipe.Ingredients} />
      <InstructionList instructions={recipe.Instructions} />
      <TagList tags={recipe.Tags} created={recipe.Created} modified={recipe.Modified} />
    </>
  ) : (
    <div className="min-h-[90vh] flex items-center justify-center gap-x-4">
      <Spinner content={"Recipe is loading..."} />
    </div>
  );
}
