import {useEffect} from 'react'
import {useMMKVObject} from 'react-native-mmkv'
import {randomUUID} from 'expo-crypto'

import tasks from '../app/tasks'
import type {ILabel} from '@/models/ILabel'

type useLabelReturnValue = {
  labels: ILabel[]
  createLabel: (name: string, color: string) => void
  deleteLabel: (id: string) => void
  updateLabel: (newLabel: Partial<ILabel> & {id: string}) => void
  getLabelById: (id: string | undefined) => ILabel | undefined
}

const useLabels = (key: string = 'labels'): useLabelReturnValue => {
  const [labels, setLabels] = useMMKVObject<ILabel[]>(key)
  const isUndefined = tasks === undefined
  // TODO: Vervang dit in de oefeningen met een Drizzle call.
  //const {deleteLabelsFromTasks} = useTasks()

  useEffect(() => {
    if (!labels) {
      setLabels([
        {id: randomUUID(), name: 'Work', color: '#625b71'},
        {id: randomUUID(), name: 'School', color: '#9a82db'},
        {id: randomUUID(), name: 'Urgent', color: '#e46962'},
      ])
    }
    // isUndefined is derived op basis van de tasks variabele, bijgevolg moet dit niet toegevoegd worden aan de
    // dependency array
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isUndefined])

  const createLabel = (name: string, color: string) => {
    setLabels([
      ...(labels ?? []),
      {
        name,
        color,
        id: randomUUID(),
      },
    ])
  }

  const updateLabel = (newLabel: Partial<ILabel> & {id: string}) => {
    setLabels(labels?.map(t => (t.id === newLabel.id ? {...t, ...newLabel} : t)))
  }

  const deleteLabel = (id: string) => {
    if (labels) {
      setLabels(labels.filter(t => t.id !== id))
      //deleteLabelsFromTasks(id)
    }
  }

  const getLabelById = (id: string | undefined): ILabel | undefined => {
    if (!id) return undefined

    return labels?.find(t => t.id === id)
  }

  return {
    labels: labels ?? [],
    createLabel,
    updateLabel,
    deleteLabel,
    getLabelById,
  }
}

export default useLabels
