import { useParams, useNavigate, Link } from "react-router-dom";
import { useState, useEffect } from "react";
import { getRecipeById, deleteRecipe, setDBStars } from "../services/frontendApi.js";
import { type Recipe, type Ingredient } from "../types/Recipe"
import Modal from '../components/Modal.tsx'
import DemoModal from '../components/DemoModal.tsx'
import StarRating from "../components/StarRating.tsx"
import TimeDisplay from '../components/TimeDisplay.tsx'

function RecipePage() {
  const [recipe, setRecipe] = useState<Recipe>({
    details: {},
    ingredients: [],
    steps: []
  });
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [stars, setStars] = useState<number>(0);
  const [initialStars, setInitialStars] = useState<number | null>(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showDemoModal, setShowDemoModal] = useState(false);
  const { id } = useParams();
  const isWebSource = recipe && recipe.details && recipe.details.author
    ? /http|com/.test(recipe.details.author) //etc
    : false;
  const navigate = useNavigate();

  const openModal = () => { setShowConfirmModal(true) };
  const closeModal = () => { setShowConfirmModal(false) };

  const confirmDelete = () => {
    if (process.env.NODE_ENV === 'demo') {
      closeModal();
      setShowDemoModal(true);
    } else {
      handleDelete(recipe.details.id);
      closeModal();
    }
  };

  useEffect(() => {
    const loadRecipe = async () => {
      try {
        const recipe = await getRecipeById(id);
        if (!recipe.details) {
          setError("Sorry, this recipe no longer exists")
        } else {
          setRecipe(recipe);
          setStars(recipe.details?.stars ?? 0)
          setInitialStars(recipe.details?.stars ?? 0);
          if (process.env.NODE_ENV === 'dev') {
            console.log(recipe)
          }
        }
      } catch (error) {
        console.log(error);
        setError("Failed to load recipes...");
      } finally {
        setLoading(false);
      }
    };
    loadRecipe();
  }, [id]);

  useEffect(() => {
    if (initialStars === null || initialStars === stars) {
      return;
    }

    const updateStarsInDB = async () => {
      await setDBStars(id, stars);
    };

    updateStarsInDB();
  }, [stars]);

  const handleDelete = async (id: number | void) => {
    try {
      await deleteRecipe(id);
      navigate('/')
    } catch (error) {
      console.error("Error deleting recipe:", error);
    }
  };
  return (
    <div className="recipe page-outer">


      {loading ? (
        <div className="loading">Loading...</div>
      ) : error ? (
        <div>
          <div className="error-message text-lg">{error}</div>
          <div className="m-2">
            <Link to="/" className="ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700">
              Return to Cookbook
            </Link>
          </div>
        </div>
      ) : (

        <div className="recipe-card relative">
          <button onClick={openModal} className="ar-button bg-amber-500 text-white py-1 px-2 rounded hover:bg-amber-600 m-2 absolute top-0 right-0">
            🗑️
          </button>
          <div className="border-b-2 border-amber-300 pb-4 mb-6">
            <h3 className="text-2xl lg:text-3xl font-bold text-amber-900 mb-2">{recipe.details.name}</h3>
            <p className="text-amber-700 italic text-lg">{recipe.details.cuisine}</p>
            <p>prep: <TimeDisplay minutes={recipe.details.prep_minutes ?? 0} /> | cook: <TimeDisplay minutes={recipe.details.cook_minutes ?? 0} /></p>
          </div>

          <div className="grid lg:grid-cols-2 gap-6 mb-6">
            <div className="bg-white rounded-lg p-4 shadow-sm border border-amber-100">
              <h4 className="text-xl font-semibold text-amber-800 mb-3 flex items-center">
                Ingredients:
              </h4>
              <ul className="space-y-2">
                {recipe.ingredients.map((ingredient: Ingredient, index) => (
                  <li key={index} className="text-gray-700 flex items-start">
                    <span className="w-1.5 h-1.5 bg-amber-400 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                    <span className="font-medium text-left">{ingredient.raw}</span>
                  </li>
                ))}
              </ul>
            </div>

            <div className="bg-white rounded-lg p-4 shadow-sm border border-amber-100">
              <h4 className="text-xl font-semibold text-amber-800 mb-3 flex items-center">
                Instructions:
              </h4>
              <ol className="space-y-3">
                {recipe.steps && Object.keys(recipe.steps || {}).map((stepNumber) => (
                  <li key={stepNumber} className="text-gray-700 flex items-start">
                    <span className="bg-amber-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mr-3 mt-0.5 flex-shrink-0">
                      {recipe.steps[parseInt(stepNumber)].step_number}
                    </span>
                    <span className="leading-relaxed text-left">{recipe.steps[parseInt(stepNumber)].instruction}</span>
                  </li>
                ))}
              </ol>
            </div>
          </div>

          <div className="border-t-2 border-amber-300 pt-4">
            <div className="flex justify-between items-center text-sm text-amber-600">
              {isWebSource ? (
                <span>Source: {recipe.details.author}</span>
              ) : (
                <span>From the kitchen of {recipe.details.author}</span>
              )}
              <span>
                <StarRating rating={stars} onRatingChange={(newRating: number) => setStars(newRating)} />
              </span>
            </div>
          </div>
        </div>
      )
      }
      <Modal
        isOpen={showConfirmModal}
        onClose={closeModal}
        message="Are you sure you want to delete this recipe?"
        confirmAction={confirmDelete}
        cancelAction={closeModal}
      />
      {showDemoModal && (
        <DemoModal
          isOpen={showDemoModal}
          onClose={() => setShowDemoModal(false)}
          closeModal={() => setShowDemoModal(false)}
        />
      )}
    </div >
  );
}

export default RecipePage;
