import {FunctionComponent} from 'react'
import {useNavigate, useParams} from 'react-router-dom'
import {useGetDrink, useUpdateDrink} from '../../api/drinksApi.ts'
import {ChevronLeft} from 'lucide-react'

const DetailPage: FunctionComponent = () => {
  const {id} = useParams()
  const {data: drink} = useGetDrink(Number(id))
  const {mutate: updateDrink} = useUpdateDrink()
  const navigate = useNavigate()

  return (
    <div className="detail-page">
      <h1>{drink.name}</h1>
      <p className="metadata subtitle">
        {drink.type} | {drink.category} | {drink.glass}
      </p>

      <p>{drink.instructions}</p>

      <p>
        <strong>Ingredients</strong>
      </p>

      <div className="ingredients">
        {drink.ingredients.map((ingredient, index) => (
          <div className="ingredient-input" key={index}>
            <input
              value={ingredient.name}
              onChange={e =>
                updateDrink({
                  ...drink,
                  ingredients: drink.ingredients.map((i, index2) =>
                    index2 === index ? {...i, name: e.target.value} : i,
                  ),
                })
              }
            />
            <input
              value={ingredient.measure}
              onChange={e =>
                updateDrink({
                  ...drink,
                  ingredients: drink.ingredients.map((i, index2) =>
                    index2 === index ? {...i, measure: e.target.value} : i,
                  ),
                })
              }
            />
          </div>
        ))}
      </div>

      <button className="back-button" onClick={() => navigate(-1)}>
        <ChevronLeft /> Back to Home
      </button>
    </div>
  )
}

export default DetailPage
