'use client'

import { Bell } from 'lucide-react'
import { usePathname, useRouter } from 'next/navigation'
import { useState, useEffect } from 'react'
import { io } from 'socket.io-client'
import { EMPLOYEE_PROFILE_KEY, EMPLOYEE_TOKEN_KEY, apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'
import { toDashboardAppPath } from '@/lib/dashboardPaths'

function computeInitials(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean)
  if (parts.length === 0) return 'U'
  if (parts.length === 1) return parts[0].slice(0, 1).toUpperCase()
  return `${parts[0].slice(0, 1)}${parts[1].slice(0, 1)}`.toUpperCase()
}

export default function TopBar() {
  const { dict } = useDashboardI18n()
  const pathname = usePathname()
  const appPath = toDashboardAppPath(pathname)
  const router = useRouter()
  const [unreadCount, setUnreadCount] = useState(0)
  const [showNotifs, setShowNotifs] = useState(false)
  const [userInitials, setUserInitials] = useState('W')
  const [notifications, setNotifications] = useState<Array<{
    id: string
    title: string
    body: string
    readAt: string | null
    createdAt: string
  }>>([])
  const [loadingNotifs, setLoadingNotifs] = useState(false)

  const [mounted, setMounted] = useState(false)
  useEffect(() => { setMounted(true) }, [])

  function getEmployeeToken() {
    if (typeof window === 'undefined') return null
    return window.localStorage.getItem(EMPLOYEE_TOKEN_KEY)
  }

  const title = (() => {
    if (!mounted) return dict.titles['/']
    if (dict.titles[appPath]) return dict.titles[appPath]
    if (appPath.startsWith('/contracts/')) return dict.titles['/contracts'] ?? dict.titles['/']
    if (appPath.startsWith('/reservations/')) return dict.titles['/reservations'] ?? dict.titles['/']
    return dict.titles['/']
  })()
  async function refreshUnreadCount() {
    if (!getEmployeeToken()) {
      setUnreadCount(0)
      return
    }

    try {
      const data = await apiFetch<{ unread: number }>('/notifications/unread-count')
      setUnreadCount(data.unread)
    } catch {}
  }

  useEffect(() => {
    refreshUnreadCount()
  }, [pathname])

  useEffect(() => {
    function onNotificationsUpdated() {
      refreshUnreadCount()
    }
    window.addEventListener('notifications:updated', onNotificationsUpdated)
    return () => window.removeEventListener('notifications:updated', onNotificationsUpdated)
  }, [])

  useEffect(() => {
    const token = window.localStorage.getItem(EMPLOYEE_TOKEN_KEY)
    if (!token) return

    const socketUrl = (process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:4000/api/v1').replace('/api/v1', '')
    const socket = io(socketUrl, { auth: { token }, transports: ['websocket'] })

    socket.on('notification', () => {
      setUnreadCount((prev) => prev + 1)
      window.dispatchEvent(new Event('notifications:updated'))
    })

    return () => { socket.disconnect() }
  }, [])

  useEffect(() => {
    if (!showNotifs) return
    if (!getEmployeeToken()) {
      setNotifications([])
      setLoadingNotifs(false)
      return
    }

    let cancelled = false
    setLoadingNotifs(true)
    apiFetch<Array<{
      id: string
      title: string
      body: string
      readAt: string | null
      createdAt: string
    }>>('/notifications/company')
      .then((data) => {
        if (cancelled) return
        setNotifications(data.slice(0, 8))
      })
      .catch(() => {
        if (cancelled) return
        setNotifications([])
      })
      .finally(() => {
        if (cancelled) return
        setLoadingNotifs(false)
      })

    return () => { cancelled = true }
  }, [showNotifs])

  useEffect(() => {
    setShowNotifs(false)
  }, [pathname])

  useEffect(() => {
    const token = window.localStorage.getItem(EMPLOYEE_TOKEN_KEY)
    if (!token) {
      setUserInitials(computeInitials(dict.workspaceUser))
      return
    }

    const cached = window.localStorage.getItem(EMPLOYEE_PROFILE_KEY)
    if (cached) {
      try {
        const profile = JSON.parse(cached) as { email?: string; firstName?: string; lastName?: string }
        const fullName = `${profile.firstName ?? ''} ${profile.lastName ?? ''}`.trim()
        const email = profile.email ?? ''
        setUserInitials(computeInitials(fullName || email || dict.workspaceUser))
      } catch {}
    }

    let cancelled = false

    apiFetch<{
      employee: {
        email: string
        firstName: string
        lastName: string
      }
    }>('/auth/employee/me')
      .then(({ employee }) => {
        if (cancelled) return
        window.localStorage.setItem(EMPLOYEE_PROFILE_KEY, JSON.stringify(employee))
        const fullName = `${employee.firstName ?? ''} ${employee.lastName ?? ''}`.trim()
        const email = employee.email ?? ''
        setUserInitials(computeInitials(fullName || email || dict.workspaceUser))
      })
      .catch(() => {
        if (cancelled) return
        setUserInitials(computeInitials(dict.workspaceUser))
      })

    return () => { cancelled = true }
  }, [dict.workspaceUser])

  async function openNotificationsInbox(notificationId?: string) {
    if (notificationId) {
      try {
        await apiFetch(`/notifications/company/${notificationId}/read`, { method: 'POST' })
        setUnreadCount((current) => Math.max(current - 1, 0))
        window.dispatchEvent(new Event('notifications:updated'))
      } catch {}
    }
    setShowNotifs(false)
    router.push('/notifications')
  }

  return (
    <header className="flex h-16 items-center justify-between border-b border-stone-200/80 bg-white/78 px-6 backdrop-blur-xl transition-colors dark:border-blue-900 dark:bg-blue-950/76">
      <h1 className="text-lg font-semibold text-blue-950 dark:text-stone-50">{title}</h1>

      <div className="flex items-center gap-3">
        <div className="relative">
          <button
            onClick={() => setShowNotifs(!showNotifs)}
            className="relative rounded-2xl p-2 text-stone-500 transition-colors hover:bg-stone-100 hover:text-stone-700 dark:text-stone-400 dark:hover:bg-blue-900/40 dark:hover:text-stone-100"
          >
            <Bell className="h-5 w-5" />
            {unreadCount > 0 ? (
              <span className="absolute right-1 top-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-bold text-white">
                {unreadCount > 99 ? '99+' : unreadCount}
              </span>
            ) : null}
          </button>

          {showNotifs ? (
            <div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-[1.75rem] border border-stone-200/80 bg-white/95 p-4 shadow-[0_20px_60px_rgba(0,0,0,0.12)] backdrop-blur dark:border-blue-900 dark:bg-blue-950/95 dark:shadow-[0_20px_60px_rgba(0,0,0,0.35)]">
              <div className="mb-2 flex items-center justify-between gap-2">
                <p className="text-sm font-medium text-blue-950 dark:text-stone-100">{dict.notifications}</p>
                <button
                  type="button"
                  onClick={() => openNotificationsInbox()}
                  className="text-xs font-medium text-orange-700 hover:text-blue-900 dark:text-orange-300 dark:hover:text-white"
                >
                  View all
                </button>
              </div>

              {loadingNotifs ? (
                <p className="text-sm text-stone-500 dark:text-stone-400">Loading…</p>
              ) : notifications.length === 0 ? (
                <p className="text-sm text-stone-500 dark:text-stone-400">
                  {unreadCount === 0 ? dict.noNewNotifications : dict.unreadNotifications(unreadCount)}
                </p>
              ) : (
                <div className="space-y-1">
                  {notifications.map((notification) => (
                    <button
                      key={notification.id}
                      type="button"
                      onClick={() => openNotificationsInbox(notification.id)}
                      className={[
                        'w-full rounded-2xl px-3 py-2 text-left transition-colors hover:bg-stone-100 dark:hover:bg-blue-900/40',
                        notification.readAt ? 'opacity-80' : '',
                      ].join(' ')}
                    >
                      <p className="truncate text-sm font-medium text-blue-950 dark:text-stone-100">
                        {notification.title}
                      </p>
                      <p className="truncate text-xs text-stone-500 dark:text-stone-400">
                        {notification.body}
                      </p>
                    </button>
                  ))}
                </div>
              )}
            </div>
          ) : null}
        </div>

        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-orange-400 text-xs font-semibold text-blue-950">
          {userInitials}
        </div>
      </div>
    </header>
  )
}
