import { FC, MouseEvent } from "react"
import { Box, Checkbox, Popover, Stack, Text, ThemeIcon } from "@mantine/core"
import {
  IconCircleCheckFilled,
  IconCircleDashed,
  IconClockHour4,
} from "@tabler/icons-react"

type TodoItem = {
  id: string
  title: string
  done: boolean
}

interface LandingTodoProgressIconProps {
  done: number
  total: number
  todoItems: TodoItem[]
  onToggle: (itemId: TodoItem["id"]) => void
  disabled?: boolean
  size?: number
}

const LandingTodoProgressIcon: FC<LandingTodoProgressIconProps> = ({
  done,
  total,
  todoItems,
  onToggle,
  disabled = false,
  size = 14,
}) => {
  const icon =
    total <= 0 || done <= 0 ? (
      <ThemeIcon variant="light" color="gray" size={size} radius="xl">
        <IconCircleDashed size={size - 5} />
      </ThemeIcon>
    ) : done >= total ? (
      <ThemeIcon variant="light" color="teal" size={size} radius="xl">
        <IconCircleCheckFilled size={size - 5} />
      </ThemeIcon>
    ) : (
      <ThemeIcon variant="light" color="yellow" size={size} radius="xl">
        <IconClockHour4 size={size - 5} />
      </ThemeIcon>
    )

  const stopRowClick = (e: MouseEvent<HTMLElement>) => {
    e.preventDefault()
    e.stopPropagation()
  }

  return (
    <Popover width={240} position="left-start" withArrow shadow="md">
      <Popover.Target>
        <Box
          component="button"
          type="button"
          onClick={stopRowClick}
          onMouseDown={stopRowClick}
          style={{
            background: "transparent",
            border: 0,
            padding: 0,
            margin: 0,
            cursor: "pointer",
            display: "inline-flex",
            alignItems: "center",
          }}
          aria-label="Открыть TODO"
        >
          {icon}
        </Box>
      </Popover.Target>
      <Popover.Dropdown onClick={e => e.stopPropagation()}>
        <Stack gap={4}>
          <Text size="xs" fw={600}>
            TODO ({done}/{Math.max(total, 0)})
          </Text>
          {todoItems.map(item => (
            <Checkbox
              key={item.id}
              size="xs"
              label={item.title}
              checked={item.done}
              disabled={disabled}
              onChange={() => onToggle(item.id)}
            />
          ))}
        </Stack>
      </Popover.Dropdown>
    </Popover>
  )
}

export default LandingTodoProgressIcon
