import type {FunctionComponent} from 'react'
import {useMemo} from 'react'
import ToDoItem from '@/components/tasks/toDoItem'
import type ILabel from '@/models/ILabel'
import type ITask from '@/models/ITask'
import {
  Accordion,
  AccordionContent,
  AccordionHeader,
  AccordionIcon,
  AccordionItem,
  AccordionTitleText,
  AccordionTrigger,
} from '@/components/ui/accordion'
import {ChevronDownIcon, ChevronUpIcon} from 'lucide-react-native'
import {LegendList} from '@legendapp/list'
import {useGetTasks} from '@/db/tasksAPI'

const TasksByLabel: FunctionComponent = () => {
  const {data: tasks} = useGetTasks()

  const [labelsWithTasks, labelMap] = useMemo(() => {
    const result: Record<string, ITask[]> = {}
    const labelMap: Record<string, ILabel> = {}

    for (const t of tasks) {
      const labels = t.labels ?? []

      for (const l of labels) {
        if (result[l.id]) {
          result[l.id].push(t)
        } else {
          result[l.id] = [t]
          labelMap[l.id] = l
        }
      }
    }
    return [result, labelMap]
  }, [tasks])

  return (
    <Accordion size="md" variant="unfilled" type="single" isCollapsible={true} isDisabled={false}>
      {Object.keys(labelMap).map(id => (
        <AccordionItem key={id} value={id}>
          <AccordionHeader>
            <AccordionTrigger>
              {({isExpanded}: {isExpanded: boolean}) => {
                return (
                  <>
                    <AccordionTitleText className="text-xl my-1">{labelMap[id].name}</AccordionTitleText>
                    <AccordionIcon as={isExpanded ? ChevronUpIcon : ChevronDownIcon} className="ml-3" />
                  </>
                )
              }}
            </AccordionTrigger>
          </AccordionHeader>
          <AccordionContent>
            <LegendList
              data={labelsWithTasks[id]}
              renderItem={({item: t}) => <ToDoItem {...t} />}
              keyExtractor={t => t.id.toString()}
            />
          </AccordionContent>
        </AccordionItem>
      ))}
    </Accordion>
  )
}

export default TasksByLabel
