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'
import {Heading} from '@/components/ui/heading'
import {VStack} from '@/components/ui/vstack'

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

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

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

      for (const label of labels) {
        if (labelToTasks[label.id]) {
          labelToTasks[label.id].push(task)
        } else {
          labelToTasks[label.id] = [task]
          labelMap[label.id] = label
        }
      }
    }
    return [labelToTasks, labelMap]
  }, [tasks])

  return (
    <>
      {Object.keys(labelsWithTasks).length === 0 && (
        <VStack className="flex items-center justify-center">
          <Heading>You haven't attached a label to a task yet</Heading>
        </VStack>
      )}
      {Object.keys(labelsWithTasks).length > 0 && (
        <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
