'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import type { BacklogItem, BacklogProgress, CategoryProgress } from './types'
import { initialBacklogItems } from './data'

const STORAGE_KEY = 'backlogItems-v2'

export function useBacklog() {
  const [items, setItems] = useState<BacklogItem[]>(initialBacklogItems)
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
  const [selectedPriority, setSelectedPriority] = useState<string | null>(null)
  const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set())
  const [searchQuery, setSearchQuery] = useState('')

  // Load saved state from localStorage
  useEffect(() => {
    const saved = localStorage.getItem(STORAGE_KEY)
    if (saved) {
      try {
        setItems(JSON.parse(saved))
      } catch (e) {
        console.error('Failed to load backlog items:', e)
      }
    }
  }, [])

  // Save state to localStorage
  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
  }, [items])

  const filteredItems = useMemo(() => {
    return items.filter((item) => {
      if (selectedCategory && item.category !== selectedCategory) return false
      if (selectedPriority && item.priority !== selectedPriority) return false
      if (searchQuery) {
        const query = searchQuery.toLowerCase()
        return (
          item.title.toLowerCase().includes(query) ||
          item.description.toLowerCase().includes(query) ||
          item.subtasks?.some((st) => st.title.toLowerCase().includes(query))
        )
      }
      return true
    })
  }, [items, selectedCategory, selectedPriority, searchQuery])

  const toggleExpand = useCallback((id: string) => {
    setExpandedItems((prev) => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      return next
    })
  }, [])

  const updateItemStatus = useCallback((id: string, status: BacklogItem['status']) => {
    setItems((prev) => prev.map((item) => (item.id === id ? { ...item, status } : item)))
  }, [])

  const toggleSubtask = useCallback((itemId: string, subtaskId: string) => {
    setItems((prev) =>
      prev.map((item) => {
        if (item.id !== itemId) return item
        return {
          ...item,
          subtasks: item.subtasks?.map((st) =>
            st.id === subtaskId ? { ...st, completed: !st.completed } : st
          ),
        }
      })
    )
  }, [])

  const progress: BacklogProgress = useMemo(() => {
    const total = items.length
    const completed = items.filter((i) => i.status === 'completed').length
    return { total, completed, percentage: Math.round((completed / total) * 100) }
  }, [items])

  const getCategoryProgress = useCallback(
    (categoryId: string): CategoryProgress => {
      const categoryItems = items.filter((i) => i.category === categoryId)
      const completed = categoryItems.filter((i) => i.status === 'completed').length
      return { total: categoryItems.length, completed }
    },
    [items]
  )

  const resetToDefaults = useCallback(() => {
    if (confirm('Backlog auf Standardwerte zuruecksetzen? Alle lokalen Aenderungen gehen verloren.')) {
      setItems(initialBacklogItems)
      localStorage.removeItem(STORAGE_KEY)
    }
  }, [])

  const clearFilters = useCallback(() => {
    setSelectedCategory(null)
    setSelectedPriority(null)
    setSearchQuery('')
  }, [])

  const hasActiveFilters = !!(selectedCategory || selectedPriority || searchQuery)

  return {
    items,
    filteredItems,
    selectedCategory,
    setSelectedCategory,
    selectedPriority,
    setSelectedPriority,
    expandedItems,
    searchQuery,
    setSearchQuery,
    toggleExpand,
    updateItemStatus,
    toggleSubtask,
    progress,
    getCategoryProgress,
    resetToDefaults,
    clearFilters,
    hasActiveFilters,
  }
}
