import { useState } from 'react'
import { useAuthStore } from '@/stores/authStore'
import { useUIStore } from '@/stores/uiStore'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Menu,
  Search,
  Bell,
  LogOut,
  User,
  Settings,
  ChevronDown,
  Building2,
} from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { getInitials, formatRelativeTime } from '@/lib/utils'
import { cn } from '@/lib/utils'

const notifications = [
  {
    id: '1',
    title: 'Nytt avtal tecknat',
    description: 'Acme Corp har signerat enterprise-avtalet',
    time: new Date(Date.now() - 1000 * 60 * 15).toISOString(),
    read: false,
  },
  {
    id: '2',
    title: 'Faktura förfallen',
    description: 'Faktura #INV-2024-0042 är 3 dagar försenad',
    time: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(),
    read: false,
  },
  {
    id: '3',
    title: 'Semester beviljad',
    description: 'Din semesteransökan har godkänts av HR',
    time: new Date(Date.now() - 1000 * 60 * 60 * 5).toISOString(),
    read: true,
  },
]

export function Header() {
  const { user, logout } = useAuthStore()
  const { toggleSidebar } = useUIStore()
  const navigate = useNavigate()
  const [notifOpen, setNotifOpen] = useState(false)
  const [profileOpen, setProfileOpen] = useState(false)

  const greeting = () => {
    const hour = new Date().getHours()
    if (hour < 12) return 'Good morning'
    if (hour < 17) return 'Good afternoon'
    return 'Good evening'
  }

  const unreadCount = notifications.filter((n) => !n.read).length

  return (
    <header className="h-16 bg-surface border-b border-border/60 flex items-center justify-between px-6 lg:px-10 sticky top-0 z-30">
      <div className="flex items-center gap-4">
        <button
          onClick={toggleSidebar}
          className="lg:hidden w-9 h-9 flex items-center justify-center rounded-xl hover:bg-bg text-text-secondary transition-colors"
        >
          <Menu size={18} />
        </button>
        <div>
          <h1 className="text-base font-semibold text-text-primary">
            {greeting()}{user ? `, ${user.name || 'Erik Svensson'}` : ', Erik Svensson'}
          </h1>
          <p className="text-xs text-text-secondary hidden sm:block">
            {new Date().toLocaleDateString('sv-SE', {
              weekday: 'long',
              year: 'numeric',
              month: 'long',
              day: 'numeric',
            })}
          </p>
        </div>
      </div>

      <div className="flex items-center gap-2">
        {/* Search */}
        <div className="hidden md:flex items-center h-9 px-3.5 rounded-xl bg-bg border border-border/60 text-text-secondary">
          <Search size={15} />
          <span className="ml-2 text-sm">Search...</span>
          <kbd className="ml-6 px-1.5 py-0.5 text-[10px] font-medium bg-surface rounded border border-border">
            ⌘K
          </kbd>
        </div>

        {/* Notifications */}
        <div className="relative">
          <button
            onClick={() => {
              setNotifOpen(!notifOpen)
              setProfileOpen(false)
            }}
            className="relative w-9 h-9 flex items-center justify-center rounded-xl hover:bg-bg text-text-secondary transition-colors"
          >
            <Bell size={17} />
            {unreadCount > 0 && (
              <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-danger rounded-full" />
            )}
          </button>

          <AnimatePresence>
            {notifOpen && (
              <>
                <div className="fixed inset-0 z-40" onClick={() => setNotifOpen(false)} />
                <motion.div
                  initial={{ opacity: 0, y: 4, scale: 0.98 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: 4, scale: 0.98 }}
                  transition={{ duration: 0.15 }}
                  className="absolute right-0 top-full mt-2 w-80 bg-surface rounded-[18px] dropdown-shadow border border-border/60 z-50 overflow-hidden"
                >
                  <div className="px-4 py-3 border-b border-border/60 flex items-center justify-between">
                    <span className="text-sm font-semibold text-text-primary">Notifications</span>
                    <span className="text-xs text-primary font-medium cursor-pointer">Mark all read</span>
                  </div>
                  <div className="max-h-80 overflow-y-auto">
                    {notifications.map((n) => (
                      <div
                        key={n.id}
                        className={cn(
                          'px-4 py-3 hover:bg-bg/60 transition-colors cursor-pointer',
                          !n.read && 'bg-primary-light/30'
                        )}
                      >
                        <div className="flex items-start gap-3">
                          <div className={cn(
                            'w-2 h-2 rounded-full mt-1.5 shrink-0',
                            n.read ? 'bg-transparent' : 'bg-primary'
                          )} />
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-text-primary">{n.title}</p>
                            <p className="text-xs text-text-secondary mt-0.5">{n.description}</p>
                            <p className="text-[11px] text-text-secondary/60 mt-1">{formatRelativeTime(n.time)}</p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </motion.div>
              </>
            )}
          </AnimatePresence>
        </div>

        {/* Profile */}
        <div className="relative">
          <button
            onClick={() => {
              setProfileOpen(!profileOpen)
              setNotifOpen(false)
            }}
            className="flex items-center gap-2 pl-1 pr-2 h-9 rounded-xl hover:bg-bg transition-colors"
          >
            <div className="w-7 h-7 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold">
              {user ? getInitials(user.name) : '?'}
            </div>
            <ChevronDown size={14} className="text-text-secondary" />
          </button>

          <AnimatePresence>
            {profileOpen && (
              <>
                <div className="fixed inset-0 z-40" onClick={() => setProfileOpen(false)} />
                <motion.div
                  initial={{ opacity: 0, y: 4, scale: 0.98 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: 4, scale: 0.98 }}
                  transition={{ duration: 0.15 }}
                  className="absolute right-0 top-full mt-2 w-56 bg-surface rounded-[18px] dropdown-shadow border border-border/60 z-50 overflow-hidden"
                >
                  <div className="px-4 py-3 border-b border-border/60">
                    <p className="text-sm font-semibold text-text-primary">{user?.name || 'User'}</p>
                    <p className="text-xs text-text-secondary">{user?.email || 'user@amos.com'}</p>
                  </div>
                  <div className="py-1">
                    <button 
                      onClick={() => { navigate('/profile'); setProfileOpen(false) }}
                      className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-text-secondary hover:bg-bg transition-colors"
                    >
                      <User size={15} />
                      Min Profil
                    </button>
                    <button className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-text-secondary hover:bg-bg transition-colors">
                      <Building2 size={15} />
                      Byt Verksamhet
                    </button>
                    <button className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-text-secondary hover:bg-bg transition-colors">
                      <Settings size={15} />
                      Inställningar
                    </button>
                    <div className="border-t border-border/60 mt-1 pt-1">
                      <button
                        onClick={() => {
                          logout()
                          setProfileOpen(false)
                        }}
                        className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-danger hover:bg-danger-light transition-colors"
                      >
                        <LogOut size={15} />
                        Sign out
                      </button>
                    </div>
                  </div>
                </motion.div>
              </>
            )}
          </AnimatePresence>
        </div>
      </div>
    </header>
  )
}
