'use client'

import { useState, useEffect } from 'react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@/components/ui/sheet'
import { Menu, Search, StickyNote, Tag, Moon, Sun, X, Bell, Trash2, Archive, Coffee } from 'lucide-react'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { cn } from '@/lib/utils'
import { useLabels } from '@/context/LabelContext'
import { LabelManagementDialog } from './label-management-dialog'
import { LabelFilter } from './label-filter'
import { NotificationPanel } from './notification-panel'
import { updateTheme } from '@/app/actions/profile'

interface HeaderProps {
  selectedLabels?: string[]
  selectedColor?: string | null
  onLabelFilterChange?: (labels: string[]) => void
  onColorFilterChange?: (color: string | null) => void
  user?: any
}

export function Header({
  selectedLabels = [],
  selectedColor = null,
  onLabelFilterChange,
  onColorFilterChange,
  user
}: HeaderProps = {}) {
  const [searchQuery, setSearchQuery] = useState('')
  const [theme, setTheme] = useState<'light' | 'dark'>('light')
  const [isSidebarOpen, setIsSidebarOpen] = useState(false)
  const pathname = usePathname()
  const router = useRouter()
  const searchParams = useSearchParams()
  const { labels } = useLabels()

  const currentLabels = searchParams.get('labels')?.split(',').filter(Boolean) || []
  const currentSearch = searchParams.get('search') || ''
  const currentColor = searchParams.get('color') || ''

  useEffect(() => {
    setSearchQuery(currentSearch)
  }, [currentSearch])

  useEffect(() => {
    const savedTheme = user?.theme || localStorage.getItem('theme') || 'light'
    // Don't persist on initial load to avoid unnecessary DB calls
    applyTheme(savedTheme, false)
  }, [user])

  const applyTheme = async (newTheme: string, persist = true) => {
    setTheme(newTheme as any)
    localStorage.setItem('theme', newTheme)
    
    // Remove all theme classes first
    document.documentElement.classList.remove('dark')
    document.documentElement.removeAttribute('data-theme')

    if (newTheme === 'dark') {
      document.documentElement.classList.add('dark')
    } else if (newTheme !== 'light') {
      document.documentElement.setAttribute('data-theme', newTheme)
      if (newTheme === 'midnight') {
         document.documentElement.classList.add('dark')
      }
    }

    if (persist && user) {
      await updateTheme(newTheme)
    }
  }

  const handleSearch = (query: string) => {
    setSearchQuery(query)
    const params = new URLSearchParams(searchParams.toString())
    if (query.trim()) {
      params.set('search', query)
    } else {
      params.delete('search')
    }
    router.push(`/?${params.toString()}`)
  }

  const removeLabelFilter = (labelToRemove: string) => {
    const newLabels = currentLabels.filter(l => l !== labelToRemove)
    const params = new URLSearchParams(searchParams.toString())
    if (newLabels.length > 0) {
      params.set('labels', newLabels.join(','))
    } else {
      params.delete('labels')
    }
    router.push(`/?${params.toString()}`)
  }

  const removeColorFilter = () => {
    const params = new URLSearchParams(searchParams.toString())
    params.delete('color')
    router.push(`/?${params.toString()}`)
  }

  const clearAllFilters = () => {
    setSearchQuery('')
    router.push('/')
  }

  const handleFilterChange = (newLabels: string[]) => {
    const params = new URLSearchParams(searchParams.toString())
    if (newLabels.length > 0) {
      params.set('labels', newLabels.join(','))
    } else {
      params.delete('labels')
    }
    router.push(`/?${params.toString()}`)
  }

  const handleColorChange = (newColor: string | null) => {
    const params = new URLSearchParams(searchParams.toString())
    if (newColor) {
      params.set('color', newColor)
    } else {
      params.delete('color')
    }
    router.push(`/?${params.toString()}`)
  }

  const toggleLabelFilter = (labelName: string) => {
    const newLabels = currentLabels.includes(labelName)
      ? currentLabels.filter(l => l !== labelName)
      : [...currentLabels, labelName]
    
    const params = new URLSearchParams(searchParams.toString())
    if (newLabels.length > 0) {
      params.set('labels', newLabels.join(','))
    } else {
      params.delete('labels')
    }
    router.push(`/?${params.toString()}`)
  }

  const NavItem = ({ href, icon: Icon, label, active, onClick }: any) => {
    const content = (
      <>
        <Icon className={cn("h-5 w-5", active && "fill-current")} />
        {label}
      </>
    )

    if (onClick) {
      return (
        <button
          onClick={onClick}
          className={cn(
            "w-full flex items-center gap-3 px-4 py-3 rounded-r-full text-sm font-medium transition-colors mr-2 text-left",
            active 
              ? "bg-amber-100 text-amber-900 dark:bg-amber-900/30 dark:text-amber-100" 
              : "hover:bg-gray-100 dark:hover:bg-zinc-800 text-gray-700 dark:text-gray-300"
          )}
        >
          {content}
        </button>
      )
    }

    return (
      <Link
        href={href}
        onClick={() => setIsSidebarOpen(false)}
        className={cn(
          "flex items-center gap-3 px-4 py-3 rounded-r-full text-sm font-medium transition-colors mr-2",
          active 
            ? "bg-amber-100 text-amber-900 dark:bg-amber-900/30 dark:text-amber-100" 
            : "hover:bg-gray-100 dark:hover:bg-zinc-800 text-gray-700 dark:text-gray-300"
        )}
      >
        {content}
      </Link>
    )
  }

  const hasActiveFilters = currentLabels.length > 0 || !!currentSearch || !!currentColor

  return (
    <>
      <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 flex flex-col transition-all duration-200">
        <div className="flex h-16 items-center px-4 gap-4 shrink-0">
          
          <Sheet open={isSidebarOpen} onOpenChange={setIsSidebarOpen}>
            <SheetTrigger asChild>
              <Button variant="ghost" size="icon" className="-ml-2 md:hidden">
                <Menu className="h-6 w-6" />
              </Button>
            </SheetTrigger>
            <SheetContent side="left" className="w-[280px] sm:w-[320px] p-0 pt-4">
              <SheetHeader className="px-4 mb-4">
                <SheetTitle className="flex items-center gap-2 text-xl font-normal text-amber-500">
                  <StickyNote className="h-6 w-6" />
                  Memento
                </SheetTitle>
              </SheetHeader>
              <div className="flex flex-col gap-1 py-2">
                <NavItem 
                  href="/" 
                  icon={StickyNote} 
                  label="Notes" 
                  active={pathname === '/' && !hasActiveFilters} 
                />
                <NavItem 
                  href="/reminders" 
                  icon={Bell} 
                  label="Reminders" 
                  active={pathname === '/reminders'} 
                />
                
                <div className="my-2 px-4 flex items-center justify-between">
                  <span className="text-xs font-medium text-gray-500 uppercase tracking-wider">Labels</span>
                  <LabelManagementDialog />
                </div>
                
                {labels.map(label => (
                  <NavItem
                    key={label.id}
                    icon={Tag}
                    label={label.name}
                    active={currentLabels.includes(label.name)}
                    onClick={() => toggleLabelFilter(label.name)}
                  />
                ))}

                <div className="my-2 border-t border-gray-200 dark:border-zinc-800" />
                
                <NavItem
                  href="/archive"
                  icon={Archive}
                  label="Archive"
                  active={pathname === '/archive'}
                />
                <NavItem
                  href="/trash"
                  icon={Trash2}
                  label="Trash"
                  active={pathname === '/trash'}
                />
                <NavItem
                  href="/support"
                  icon={Coffee}
                  label="Support ☕"
                  active={pathname === '/support'}
                />
              </div>
            </SheetContent>
          </Sheet>

          <Link href="/" className="flex items-center gap-2 mr-4">
            <StickyNote className="h-7 w-7 text-amber-500" />
            <span className="font-medium text-xl hidden sm:inline-block text-gray-600 dark:text-gray-200">
              Memento
            </span>
          </Link>

          <div className="flex-1 max-w-2xl relative">
            <div className="relative group">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 group-focus-within:text-gray-600 dark:group-focus-within:text-gray-200 transition-colors" />
              <Input
                placeholder="Search"
                className="pl-10 pr-12 h-11 bg-gray-100 dark:bg-zinc-800/50 border-transparent focus:bg-white dark:focus:bg-zinc-900 focus:border-gray-200 dark:focus:border-zinc-700 shadow-none transition-all"
                value={searchQuery}
                onChange={(e) => handleSearch(e.target.value)}
              />
              {searchQuery && (
                <button 
                  onClick={() => handleSearch('')}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
                >
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
            <div className="absolute right-0 top-0 h-full flex items-center pr-2">
              <LabelFilter
                selectedLabels={currentLabels}
                onFilterChange={handleFilterChange}
              />
            </div>
          </div>

          <div className="flex items-center gap-1 sm:gap-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon">
                  {theme === 'light' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => applyTheme('light')}>Light</DropdownMenuItem>
                <DropdownMenuItem onClick={() => applyTheme('dark')}>Dark</DropdownMenuItem>
                <DropdownMenuItem onClick={() => applyTheme('midnight')}>Midnight</DropdownMenuItem>
                <DropdownMenuItem onClick={() => applyTheme('sepia')}>Sepia</DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>

            <NotificationPanel />
          </div>
        </div>

        {hasActiveFilters && (
          <div className="px-4 pb-3 flex items-center gap-2 overflow-x-auto border-t border-gray-100 dark:border-zinc-800 pt-2 bg-white/50 dark:bg-zinc-900/50 backdrop-blur-sm animate-in slide-in-from-top-2">
            {currentSearch && (
              <Badge variant="secondary" className="flex items-center gap-1 h-7 whitespace-nowrap pl-2 pr-1">
                Search: {currentSearch}
                <button onClick={() => handleSearch('')} className="ml-1 hover:bg-black/10 dark:hover:bg-white/10 rounded-full p-0.5">
                  <X className="h-3 w-3" />
                </button>
              </Badge>
            )}
            {currentColor && (
              <Badge variant="secondary" className="flex items-center gap-1 h-7 whitespace-nowrap pl-2 pr-1">
                <div className={cn("w-3 h-3 rounded-full border border-black/10", `bg-${currentColor}-500`)} />
                Color: {currentColor}
                <button onClick={removeColorFilter} className="ml-1 hover:bg-black/10 dark:hover:bg-white/10 rounded-full p-0.5">
                  <X className="h-3 w-3" />
                </button>
              </Badge>
            )}
            {currentLabels.map(label => (
              <Badge key={label} variant="secondary" className="flex items-center gap-1 h-7 whitespace-nowrap pl-2 pr-1">
                <Tag className="h-3 w-3" />
                {label}
                <button onClick={() => removeLabelFilter(label)} className="ml-1 hover:bg-black/10 dark:hover:bg-white/10 rounded-full p-0.5">
                  <X className="h-3 w-3" />
                </button>
              </Badge>
            ))}
            
            <Button 
              variant="ghost" 
              size="sm" 
              onClick={clearAllFilters}
              className="h-7 text-xs text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20 whitespace-nowrap ml-auto"
            >
              Clear all
            </Button>
          </div>
        )}
      </header>
    </>
  )
}
