import {FunctionComponent, useContext, useState} from 'react'
import Drink from './drink.tsx'
import {useDeleteDrink, useGetDrinks} from '../../api/drinksApi.ts'
import {DrinkType} from '../../models/IDrink.ts'
import {SelectedDrinkContext} from '../../context/selectedDrinkProvider.tsx'
import LoadingPart from '../../components/loadingPart.tsx'

type DrinkTypeFilter = 'All' | DrinkType

const HomePage: FunctionComponent = () => {
  const {data: drinks} = useGetDrinks()
  const {mutate: deleteDrink, isPending} = useDeleteDrink()
  const {selectedDrinkIds, resetSelectedDrinkIds} = useContext(SelectedDrinkContext)
  const [typeFilter, setTypeFilter] = useState<DrinkTypeFilter>('All')
  const [nameFilter, setNameFilter] = useState<string>('')

  return (
    <div>
      <h1>Drinks</h1>

      <div className="filters">
        <div className="form-element">
          <label htmlFor="drink-type-filter">Type:</label>
          <select
            id="drink-type-filter"
            value={typeFilter}
            onChange={e => setTypeFilter(e.target.value as DrinkTypeFilter)}>
            <option value="All">All</option>
            <option value="Alcoholic">Alcoholic</option>
            <option value="Non alcoholic">Non alcoholic</option>
          </select>
        </div>
        <div className="form-element">
          <label htmlFor="drink-name-filter">Name:</label>
          <input
            id="drink-name-filter"
            value={nameFilter}
            onChange={e => setNameFilter(e.target.value)}
            type="text"
            placeholder="Filter drinks by name"
          />
        </div>
      </div>

      <div className="delete-drinks">
        <div>
          <strong>{selectedDrinkIds.size}</strong> drinks selected
        </div>
        <button className="delete-button" disabled={selectedDrinkIds.size === 0} onClick={resetSelectedDrinkIds}>
          Clear selection
        </button>
        <button
          className="delete-button"
          disabled={selectedDrinkIds.size === 0}
          onClick={() => {
            deleteDrink({ids: Array.from(selectedDrinkIds)})
            resetSelectedDrinkIds()
          }}>
          {isPending && <LoadingPart />} Delete selection
        </button>
      </div>

      <div className="drinks-container">
        {drinks
          .filter(
            d =>
              d.name.toLowerCase().includes(nameFilter.toLowerCase()) &&
              (typeFilter === 'All' || d.type === typeFilter),
          )
          .map(d => (
            <Drink {...d} key={d.id} />
          ))}
      </div>
    </div>
  )
}

export default HomePage
