"use client"

import { useState } from "react"
import Link from "next/link"
import { useUserInterfaceStore } from "@/lib/stores/user-interface-store"
import { useUserProfile } from "@/lib/queries/use-user-profile"
import { signOut } from "../actions"
import {
  NotificationPanel,
  useUnviewedNotificationCount,
} from "./notification-panel"

export function SidebarFooter() {
  const toggleSidebar = useUserInterfaceStore((state) => state.toggleSidebar)
  const setActiveSettingsTab = useUserInterfaceStore(
    (state) => state.setActiveSettingsTab
  )
  const [isNotificationPanelOpen, setIsNotificationPanelOpen] = useState(false)
  const unviewedNotificationCount = useUnviewedNotificationCount()
  const { data: userProfile } = useUserProfile()

  const displayName = userProfile?.displayName ?? "account"

  function closeSidebarOnMobile() {
    if (typeof window !== "undefined" && window.innerWidth < 768) {
      toggleSidebar()
    }
  }

  return (
    <div data-sidebar-footer className="border-t border-border p-2">
      <Link
        href="/reader/settings"
        onClick={() => {
          setActiveSettingsTab("account")
          closeSidebarOnMobile()
        }}
        className="block whitespace-nowrap truncate px-2 py-1 text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
      >
        {displayName}
      </Link>
      <div className="relative">
        <button
          type="button"
          data-notification-toggle
          onClick={() => setIsNotificationPanelOpen(!isNotificationPanelOpen)}
          className="flex w-full items-center whitespace-nowrap px-2 py-1 text-left text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
        >
          notifications
          {unviewedNotificationCount > 0 && (
            <span className="ml-auto shrink-0 text-[0.625rem] tabular-nums text-text-dim">
              {unviewedNotificationCount > 999 ? "999+" : unviewedNotificationCount}
            </span>
          )}
        </button>
        {isNotificationPanelOpen && (
          <NotificationPanel
            onClose={() => setIsNotificationPanelOpen(false)}
          />
        )}
      </div>
      <Link
        href="/reader/settings"
        onClick={closeSidebarOnMobile}
        className="block whitespace-nowrap px-2 py-1 text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
      >
        settings
      </Link>
      <form action={signOut}>
        <button
          type="submit"
          onClick={closeSidebarOnMobile}
          className="w-full whitespace-nowrap px-2 py-1 text-left text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
        >
          sign out
        </button>
      </form>
    </div>
  )
}
