'use client'

import { useState, useEffect, useRef } 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, Sparkles, Grid3x3, Settings, LogOut, User, Shield, 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 { LabelFilter } from './label-filter'
import { NotificationPanel } from './notification-panel'
import { updateTheme } from '@/app/actions/profile'
import { useDebounce } from '@/hooks/use-debounce'
import { useLanguage } from '@/lib/i18n'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { useSession, signOut } from 'next-auth/react'

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 [isSemanticSearching, setIsSemanticSearching] = useState(false)
  const pathname = usePathname()
  const router = useRouter()
  const searchParams = useSearchParams()
  const { labels, setNotebookId } = useLabels()
  const { t } = useLanguage()
  const { data: session } = useSession()

  // Track last pushed search to avoid infinite loops
  const lastPushedSearch = useRef<string | null>(null)

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

  const currentUser = user || session?.user

  // Initialize search query from URL ONLY on mount
  useEffect(() => {
    setSearchQuery(currentSearch)
    lastPushedSearch.current = currentSearch
  }, []) // Run only once on mount

  // Sync LabelContext notebookId with URL notebook parameter
  const currentNotebook = searchParams.get('notebook')
  useEffect(() => {
    setNotebookId(currentNotebook || null)
  }, [currentNotebook, setNotebookId])

  // Simple debounced search with URL update (150ms for more responsiveness)
  const debouncedSearchQuery = useDebounce(searchQuery, 150)

  useEffect(() => {
    // Skip if search hasn't changed or if we already pushed this value
    if (debouncedSearchQuery === lastPushedSearch.current) return

    // Build new params preserving other filters
    const params = new URLSearchParams(searchParams.toString())
    if (debouncedSearchQuery.trim()) {
      params.set('search', debouncedSearchQuery)
    } else {
      params.delete('search')
    }

    const newUrl = `/?${params.toString()}`

    // Mark as pushed before calling router.push to prevent loops
    lastPushedSearch.current = debouncedSearchQuery
    router.push(newUrl)
  }, [debouncedSearchQuery])

  // Handle semantic search button click
  const handleSemanticSearch = () => {
    if (!searchQuery.trim()) return

    // Add semantic flag to URL
    const params = new URLSearchParams(searchParams.toString())
    params.set('search', searchQuery)
    params.set('semantic', 'true')
    router.push(`/?${params.toString()}`)

    // Show loading state briefly
    setIsSemanticSearching(true)
    setTimeout(() => setIsSemanticSearching(false), 1500)
  }

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

  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 && currentUser) {
      await updateTheme(newTheme)
    }
  }

  const handleSearch = (query: string) => {
    setSearchQuery(query)
    // URL update is now handled by the debounced useEffect
  }

  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 = () => {
    // Clear only label and color filters, keep search
    const params = new URLSearchParams(searchParams.toString())
    params.delete('labels')
    params.delete('color')
    router.push(`/?${params.toString()}`)
  }

  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 text-amber-900")} />
        {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-[#EFB162] text-amber-900"
              : "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-[#EFB162] text-amber-900"
            : "hover:bg-gray-100 dark:hover:bg-zinc-800 text-gray-700 dark:text-gray-300"
        )}
      >
        {content}
      </Link>
    )
  }

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

  return (
    <>
      <header className="h-20 bg-background-light/90 dark:bg-background-dark/90 backdrop-blur-sm border-b border-transparent flex items-center justify-between px-6 lg:px-12 flex-shrink-0 z-30 sticky top-0">
        {/* Mobile Menu Button */}
        <Sheet open={isSidebarOpen} onOpenChange={setIsSidebarOpen}>
          <SheetTrigger asChild>
            <Button variant="ghost" size="icon" className="lg:hidden mr-4 text-slate-500 dark:text-slate-400">
              <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">
                <StickyNote className="h-6 w-6 text-amber-500" />
                {t('nav.workspace')}
              </SheetTitle>
            </SheetHeader>
            <div className="flex flex-col gap-1 py-2">
              <NavItem
                href="/"
                icon={StickyNote}
                label={t('nav.notes')}
                active={pathname === '/' && !hasActiveFilters}
              />
              <NavItem
                href="/reminders"
                icon={Bell}
                label={t('reminder.title')}
                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">{t('labels.title')}</span>
              </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={Settings}
                label={t('nav.archive')}
                active={pathname === '/archive'}
              />
              <NavItem
                href="/trash"
                icon={Tag}
                label={t('nav.trash')}
                active={pathname === '/trash'}
              />
            </div>
          </SheetContent>
        </Sheet>

        {/* Search Bar */}
        <div className="flex-1 max-w-2xl flex items-center bg-white dark:bg-slate-800/80 rounded-2xl px-4 py-3 shadow-sm border border-transparent focus-within:border-indigo-500/50 focus-within:ring-2 ring-indigo-500/10 transition-all">
          <Search className="text-slate-400 dark:text-slate-500 text-xl" />
          <input
            className="bg-transparent border-none outline-none focus:ring-0 w-full text-sm text-slate-700 dark:text-slate-200 ml-3 placeholder-slate-400"
            placeholder={t('search.placeholder') || "Search notes, tags, or notebooks..."}
            type="text"
            value={searchQuery}
            onChange={(e) => handleSearch(e.target.value)}
          />

          {/* IA Search Button */}
          <button
            onClick={handleSemanticSearch}
            disabled={!searchQuery.trim() || isSemanticSearching}
            className={cn(
              "flex items-center gap-1 px-2 py-1.5 rounded-md text-xs font-medium transition-colors",
              "hover:bg-indigo-100 dark:hover:bg-indigo-900/30",
              searchParams.get('semantic') === 'true'
                ? "bg-indigo-200 dark:bg-indigo-900/50 text-indigo-900 dark:text-indigo-100"
                : "text-gray-500 dark:text-gray-400 hover:text-indigo-700 dark:hover:text-indigo-300",
              "disabled:opacity-50 disabled:cursor-not-allowed"
            )}
            title={t('search.semanticTooltip')}
          >
            <Sparkles className={cn("h-3.5 w-3.5", isSemanticSearching && "animate-spin")} />
          </button>

          {searchQuery && (
            <button
              onClick={() => handleSearch('')}
              className="ml-2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-200"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>

        {/* Right Side Actions */}
        <div className="flex items-center space-x-3 ml-6">
          {/* Label Filter */}
          <LabelFilter
            selectedLabels={currentLabels}
            onFilterChange={handleFilterChange}
          />

          {/* Grid View Button */}
          <button className="p-2.5 text-slate-500 hover:bg-white hover:shadow-sm dark:text-slate-400 dark:hover:bg-slate-700 rounded-xl transition-all duration-200">
            <Grid3x3 className="text-xl" />
          </button>

          {/* Theme Toggle */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button className="p-2.5 text-slate-500 hover:bg-white hover:shadow-sm dark:text-slate-400 dark:hover:bg-slate-700 rounded-xl transition-all duration-200">
                {theme === 'light' ? <Sun className="text-xl" /> : <Moon className="text-xl" />}
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => applyTheme('light')}>{t('settings.themeLight')}</DropdownMenuItem>
              <DropdownMenuItem onClick={() => applyTheme('dark')}>{t('settings.themeDark')}</DropdownMenuItem>
              <DropdownMenuItem onClick={() => applyTheme('midnight')}>Midnight</DropdownMenuItem>
              <DropdownMenuItem onClick={() => applyTheme('sepia')}>Sepia</DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>

          {/* Notifications */}
          <NotificationPanel />
        </div>
      </header>

      {/* Active Filters Bar */}
      {hasActiveFilters && (
        <div className="px-6 lg:px-12 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">
          {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`)} />
              {t('notes.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>
          ))}

          {(currentLabels.length > 0 || currentColor) && (
            <Button
              variant="ghost"
              size="sm"
              onClick={clearAllFilters}
              className="h-7 text-xs text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50 dark:text-indigo-400 dark:hover:bg-indigo-900/20 whitespace-nowrap ml-auto"
            >
              {t('labels.clearAll')}
            </Button>
          )}
        </div>
      )}
    </>
  )
}
