import { FC, useCallback, useMemo, useState } from "react"
import { Button, Group, ScrollArea, Stack, Text, TextInput } from "@mantine/core"
import { LandingShortType, useUpdateLandingTodoMutation } from "@/models/landings"
import LandingTodoProgressIcon from "@/shared/ui/LandingTodoProgressIcon"

interface ServiceLandingSelectableListProps {
  landings: LandingShortType[]
  selectedKey: string | undefined
  onSelect: (key: string) => void
}

const ServiceLandingSelectableList: FC<ServiceLandingSelectableListProps> = ({
  landings,
  selectedKey,
  onSelect,
}) => {
  const [query, setQuery] = useState("")
  const [updateTodo, updateTodoState] = useUpdateLandingTodoMutation()

  const handleFilterChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setQuery(e.currentTarget.value)
    },
    []
  )

  const filteredLandings = useMemo(() => {
    if (!landings) return []
    return landings.filter(item =>
      item.label.toLowerCase().includes(query.toLowerCase())
    )
  }, [landings, query])

  const handleTodoToggle = useCallback(
    async (landing: LandingShortType, itemId: string) => {
      const slash = landing.path.indexOf("/")
      const serviceKey = slash >= 0 ? landing.path.slice(0, slash) : ""
      const landingKey = slash >= 0 ? landing.path.slice(slash + 1) : landing.path
      if (!serviceKey || !landingKey) return
      const items = landing.todoItems.map(item =>
        item.id === itemId ? { ...item, done: !item.done } : item
      )
      await updateTodo({ serviceKey, landingKey, items }).unwrap()
    },
    [updateTodo]
  )

  return (
    <Stack gap="sm" h="100%" mih={0}>
      <TextInput
        placeholder="Фильтр по папке или пути…"
        value={query}
        onChange={handleFilterChange}
        autoComplete="off"
        size="xs"
      />
      <ScrollArea flex={1} type="auto" offsetScrollbars>
        <Stack gap={0}>
          {filteredLandings.map(item => (
            <Button
              key={item.path}
              fullWidth
              justify="flex-start"
              variant={item.path === selectedKey ? "light" : "subtle"}
              color={item.path === selectedKey ? "blue" : "gray"}
              size="compact-sm"
              styles={{
                label: {
                  alignItems: "flex-start",
                  textAlign: "left",
                  width: "100%",
                },
              }}
              onClick={() => onSelect(item.path)}
            >
              <Stack gap={2} w="100%">
                <Group gap={6} wrap="nowrap" justify="space-between">
                  <Text size="xs" lineClamp={2} style={{ flex: 1, minWidth: 0 }}>
                    {item.label}
                  </Text>
                  <LandingTodoProgressIcon
                    done={item.todoDone}
                    total={item.todoTotal}
                    todoItems={item.todoItems}
                    disabled={updateTodoState.isLoading}
                    onToggle={itemId => handleTodoToggle(item, itemId)}
                  />
                </Group>
                <Text size="10px" c="dimmed" lineClamp={2}>
                  {item.path}
                </Text>
              </Stack>
            </Button>
          ))}
        </Stack>
      </ScrollArea>
    </Stack>
  )
}

export default ServiceLandingSelectableList
