import { useEffect, useState } from "react"
import { NavLink, useNavigate } from "react-router-dom"
import {
  Users,
  LayoutDashboard,
  X,
  PanelLeftClose,
  PanelLeftOpen,
  PanelRightClose,
  PanelRightOpen,
  Briefcase,
  ChartColumn,
  Clock3,
  History,
  Tags,
  User,
  Globe,
  LogOut,
  LogIn,
  FlaskConical,
  RefreshCcw,
} from "lucide-react"
import { toast } from "sonner"

import { useOptionalWorkspace } from "../context/WorkspaceContext"
import { useTranslation } from "../hooks/useTranslation"
import { canWorkspace, WORKSPACE_LOGS_VIEW } from "../lib/permissions"
import { WorkspaceSelector } from "./WorkspaceSelector"
import { SettingsMenu } from "./SettingsMenu"
import { Button } from "./ui/button"
import { getUserProfile, logoutUser } from "../api/users"
import { clearSessionTokens, getAccessToken, getRefreshToken, setDemoSessionMeta, setSessionTokens } from "../lib/session"
import { startDemo } from "../api/demo"

type SidebarProps = {
  mobileOpen?: boolean
  onMobileClose?: () => void
}

export const Sidebar = ({ mobileOpen = false, onMobileClose }: SidebarProps) => {
  const [isCollapsed, setIsCollapsed] = useState(false)
  const [showLogoutModal, setShowLogoutModal] = useState(false)
  const [isResettingDemo, setIsResettingDemo] = useState(false)
  const [user, setUser] = useState<any>(null)

  const navigate = useNavigate()
  const { t, lang, setLanguage } = useTranslation()

  const workspaceContext = useOptionalWorkspace()
  const activeWorkspace = workspaceContext?.activeWorkspace ?? null

  const isRtl = lang === "fa"
  const canViewLogs = canWorkspace(activeWorkspace?.my_role, WORKSPACE_LOGS_VIEW)
  const isDemoUser = Boolean(user?.is_demo)
  const demoExpiryLabel = user?.demo_expires_at
    ? new Intl.DateTimeFormat(isRtl ? "fa-IR" : "en-US", {
        dateStyle: "medium",
        timeStyle: "short",
      }).format(new Date(user.demo_expires_at))
    : null

  const ToggleIcon = isRtl
    ? isCollapsed
      ? PanelRightOpen
      : PanelRightClose
    : isCollapsed
      ? PanelLeftOpen
      : PanelLeftClose

  useEffect(() => {
    const handleProfileUpdated = ((e: CustomEvent) => {
      if (e.detail) {
        setUser((prev: any) => (prev ? { ...prev, ...e.detail } : e.detail))
      }
    }) as EventListener

    window.addEventListener("profile_updated", handleProfileUpdated)
    return () => window.removeEventListener("profile_updated", handleProfileUpdated)
  }, [])

  useEffect(() => {
    const fetchUser = async () => {
      const token = getAccessToken()
      if (!token) return

      try {
        const userData = await getUserProfile()
        setUser(userData)
      } catch (error) {
        console.error("Failed to fetch user profile:", error)
      }
    }

    void fetchUser()
  }, [])

  const handleLogout = async () => {
    try {
      const refreshToken = getRefreshToken()
      if (refreshToken) {
        await logoutUser(refreshToken)
      }
    } catch (error) {
      console.error("Logout API failed:", error)
    } finally {
      clearSessionTokens()
      setUser(null)
      setShowLogoutModal(false)
      onMobileClose?.()
      toast.success(t.logoutToast || "Successfully logged out!")
      navigate("/auth")
    }
  }

  const handleResetDemo = async () => {
    if (isResettingDemo) return
    setIsResettingDemo(true)
    try {
      const demo = await startDemo()
      setSessionTokens(demo.access, demo.refresh)
      setDemoSessionMeta(demo.expires_at)
      toast.success(t.demo?.reset || "Fresh demo environment is ready.")
      window.location.href = "/timesheet"
    } catch (error) {
      console.error("Demo reset failed:", error)
      toast.error(t.demo?.startError || "Could not start the demo environment.")
    } finally {
      setIsResettingDemo(false)
    }
  }

  const toggleLanguage = () => {
    const newLang = isRtl ? "en" : "fa"

    if (setLanguage) {
      setLanguage(newLang)
    } else {
      localStorage.setItem("language", newLang)
      window.location.reload()
    }
  }

  const navItems = [
    {
      path: "/timesheet",
      icon: Clock3,
      label: t.sidebar?.timesheet || "Timesheet",
    },
    {
      path: "/tags",
      icon: Tags,
      label: t.sidebar?.tags || "Tags",
    },
    {
      path: "/clients",
      icon: Users,
      label: t.sidebar?.clients || "Clients",
    },
    {
      path: "/projects",
      icon: Briefcase,
      label: t.sidebar?.projects || "Projects",
    },
    {
      path: "/workspaces",
      icon: LayoutDashboard,
      label: t.sidebar?.workspaces || "Workspaces",
    },
    {
      path: "/reports",
      icon: ChartColumn,
      label: t.sidebar?.reports || "Reports",
    },
    ...(canViewLogs
      ? [
          {
            path: "/logs",
            icon: History,
            label: t.sidebar?.logs || "Logs",
          },
        ]
      : []),
  ]

  const renderNavItems = (mobile = false) =>
    navItems.map((item) => {
      const Icon = item.icon

      return (
        <NavLink
          key={`${mobile ? "mobile" : "desktop"}-${item.path}`}
          to={item.path}
          title={!mobile && isCollapsed ? item.label : undefined}
          onClick={() => {
            if (mobile) onMobileClose?.()
          }}
          className={({ isActive }) =>
            `flex items-center rounded-lg text-sm font-medium transition-colors ${
              mobile
                ? "gap-3 px-4 py-3"
                : isCollapsed
                  ? "justify-center px-0 py-2.5"
                  : "gap-3 px-3 py-2.5"
            } ${
              isActive
                ? "bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400"
                : "text-slate-600 hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
            }`
          }
        >
          <Icon size={mobile ? 20 : isCollapsed ? 22 : 18} className="shrink-0" />

          {(mobile || !isCollapsed) && (
            <span className="truncate whitespace-nowrap">{item.label}</span>
          )}
        </NavLink>
      )
    })

  const renderMobileTopSection = () => {
    if (!user) {
      return null
    }

    return (
      <div className="border-b border-slate-200 p-4 dark:border-slate-800">
        <div className="w-full">
          <WorkspaceSelector className="w-full" />
        </div>
        {isDemoUser && (
          <div className="mt-3 rounded-2xl border border-cyan-200 bg-cyan-50 p-3 text-xs font-medium text-cyan-800 dark:border-cyan-500/20 dark:bg-cyan-500/10 dark:text-cyan-100">
            <div className="flex items-center gap-2 font-semibold">
              <FlaskConical className="h-4 w-4" />
              {t.demo?.badge || "Demo environment"}
            </div>
            {demoExpiryLabel && (
              <div className="mt-1 text-cyan-700 dark:text-cyan-300">
                {(t.demo?.expiresAt || "Expires at")}: {demoExpiryLabel}
              </div>
            )}
          </div>
        )}
      </div>
    )
  }

  const renderMobileFooterSection = () => {
    if (!user) {
      return (
        <div className="border-t border-slate-200 p-4 dark:border-slate-800">
          <button
            onClick={toggleLanguage}
            className="flex w-full items-center gap-3 rounded-lg px-4 py-3 mb-3 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
          >
            <Globe size={20} className="shrink-0" />
            <span className="truncate whitespace-nowrap">
              {isRtl ? "English" : "فارسی"}
            </span>
          </button>

          <Button
            onClick={() => {
              onMobileClose?.()
              navigate("/auth")
            }}
            className="w-full bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700"
          >
            <LogIn className="mr-2 h-4 w-4" />
            {t.login?.signIn || "Login"}
          </Button>
        </div>
      )
    }

    return (
      <div className="space-y-1 p-4">
        <button
          onClick={() => {
            onMobileClose?.()
            navigate("/profile")
          }}
          className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
        >
          <User size={20} className="shrink-0" />
          <span className="truncate whitespace-nowrap">
            {t.profile?.title || "Profile"}
          </span>
        </button>

        <button
          onClick={toggleLanguage}
          className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
        >
          <Globe size={20} className="shrink-0" />
          <span className="truncate whitespace-nowrap">
            {isRtl ? "English" : "فارسی"}
          </span>
        </button>

        {isDemoUser && (
          <button
            onClick={handleResetDemo}
            disabled={isResettingDemo}
            className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-sm font-medium text-cyan-700 transition-colors hover:bg-cyan-50 disabled:cursor-not-allowed disabled:opacity-70 dark:text-cyan-300 dark:hover:bg-cyan-950/40"
          >
            <RefreshCcw size={20} className="shrink-0" />
            <span className="truncate whitespace-nowrap">
              {isResettingDemo ? t.demo?.starting || "Preparing demo..." : t.demo?.resetAction || "Reset demo"}
            </span>
          </button>
        )}

        <button
          onClick={() => setShowLogoutModal(true)}
          className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-sm font-medium text-red-600 transition-colors hover:bg-red-50 dark:text-red-500 dark:hover:bg-red-950/50"
        >
          <LogOut size={20} className="shrink-0" />
          <span className="truncate whitespace-nowrap">{t.logout || "Logout"}</span>
        </button>
      </div>
    )
  }

  return (
    <>
      {/* Desktop sidebar */}
      <aside
        className={`hidden h-screen shrink-0 flex-col border-e border-slate-200 bg-white transition-all duration-300 ease-in-out md:sticky md:top-0 md:flex dark:border-slate-800 dark:bg-slate-950 ${
          isCollapsed ? "w-20" : "w-64"
        }`}
      >
        <div
          className={`flex h-[73px] shrink-0 items-center border-b border-slate-200 transition-all dark:border-slate-800 ${
            isCollapsed ? "justify-center px-0" : "justify-between px-6"
          }`}
        >
          {!isCollapsed && (
            <h2 className="truncate text-xl font-bold text-slate-800 dark:text-white">
              {t.title || "Qlockify"}
            </h2>
          )}

          <button
            onClick={() => setIsCollapsed(!isCollapsed)}
            className="rounded-lg p-2 text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
            title={
              isCollapsed
                ? t.sidebar?.expand || "Expand"
                : t.sidebar?.collapse || "Collapse"
            }
          >
            <ToggleIcon size={20} />
          </button>
        </div>

        <nav className="flex-1 space-y-1 overflow-y-auto overflow-x-hidden p-4">
          {isDemoUser && !isCollapsed && (
            <div className="mb-3 rounded-2xl border border-cyan-200 bg-cyan-50 p-3 text-xs font-medium text-cyan-800 dark:border-cyan-500/20 dark:bg-cyan-500/10 dark:text-cyan-100">
              <div className="flex items-center gap-2 font-semibold">
                <FlaskConical className="h-4 w-4" />
                {t.demo?.badge || "Demo environment"}
              </div>
              {demoExpiryLabel && (
                <div className="mt-1 text-cyan-700 dark:text-cyan-300">
                  {(t.demo?.expiresAt || "Expires at")}: {demoExpiryLabel}
                </div>
              )}
              <button
                type="button"
                onClick={handleResetDemo}
                disabled={isResettingDemo}
                className="mt-2 inline-flex items-center gap-2 rounded-full bg-cyan-600 px-3 py-1.5 text-white transition hover:bg-cyan-700 disabled:cursor-not-allowed disabled:opacity-70 dark:bg-cyan-400 dark:text-slate-950 dark:hover:bg-cyan-300"
              >
                <RefreshCcw className="h-3.5 w-3.5" />
                {isResettingDemo ? t.demo?.starting || "Preparing demo..." : t.demo?.resetAction || "Reset demo"}
              </button>
            </div>
          )}
          {renderNavItems(false)}
        </nav>
      </aside>

      {/* Mobile sidebar */}
      <div
        className={`fixed inset-0 z-[70] transition-all duration-200 md:hidden ${
          mobileOpen ? "pointer-events-auto" : "pointer-events-none"
        }`}
        aria-hidden={!mobileOpen}
      >
        <button
          type="button"
          className={`absolute inset-0 bg-slate-950/50 backdrop-blur-[1px] transition-opacity ${
            mobileOpen ? "opacity-100" : "opacity-0"
          }`}
          onClick={onMobileClose}
        />

        <aside
          dir={isRtl ? "rtl" : "ltr"}
          className={`absolute inset-y-0 flex w-[19.5rem] max-w-[88vw] flex-col overflow-hidden bg-white shadow-2xl transition-transform dark:bg-slate-950 ${
            isRtl
              ? `right-0 border-s border-slate-200 dark:border-slate-800 ${
                  mobileOpen ? "translate-x-0" : "translate-x-full"
                }`
              : `left-0 border-e border-slate-200 dark:border-slate-800 ${
                  mobileOpen ? "translate-x-0" : "-translate-x-full"
                }`
          }`}
        >
          <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
            <div className="flex shrink-0 items-center justify-between border-b border-slate-200 px-5 py-5 dark:border-slate-800">
              <h2 className="truncate text-lg font-bold text-slate-800 dark:text-white">
                {t.title || "Qlockify"}
              </h2>

              <button
                type="button"
                onClick={onMobileClose}
                className="rounded-lg p-2 text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
                title="Close"
              >
                <X size={20} />
              </button>
            </div>

            <div className="shrink-0">
              {renderMobileTopSection()}
            </div>

            <nav className="shrink-0 space-y-1 p-4">
              {renderNavItems(true)}
            </nav>

            <div className="mt-auto shrink-0">
              {renderMobileFooterSection()}
            </div>
          </div>
        </aside>
      </div>

      {showLogoutModal && (
        <div
          className="fixed inset-0 z-[90] flex items-center justify-center bg-black/50 px-4"
          onClick={() => setShowLogoutModal(false)}
        >
          <div
            className="w-full max-w-sm rounded-lg border bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="mb-2 text-lg font-bold text-slate-900 dark:text-white">
              {t.confirmLogoutTitle || "Confirm Logout"}
            </h2>

            <p className="mb-6 text-slate-600 dark:text-slate-400">
              {t.confirmLogoutMessage ||
                "Are you sure you want to log out of your account?"}
            </p>

            <div className="flex justify-end gap-3">
              <Button
                variant="outline"
                onClick={() => setShowLogoutModal(false)}
                className="dark:text-white"
              >
                {t.actions?.cancel || "Cancel"}
              </Button>

              <Button
                variant="destructive"
                onClick={handleLogout}
                className="bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700"
              >
                {t.logout || "Logout"}
              </Button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
