"use client"

import { getUserOrganizations } from "@/components/dashboard/action"
import { UserProfile } from "@auth0/nextjs-auth0/client"
import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  useMemo,
  useRef,
  useCallback,
} from "react"

export type ViewMode = "personal" | "organization"

type ViewModeContextType = {
  mode: ViewMode
  currentOrg?: Organization | null
  orgs: Organization[]
  loading: boolean
  switchToMode: (mode: ViewMode, orgId?: string) => Promise<void>
}

const ViewModeContext = createContext<ViewModeContextType>({
  loading: true,
  mode: "personal",
  currentOrg: undefined,
  orgs: [],
  switchToMode: async () => Promise.resolve(),
})

interface Organization {
  id: string
  name: string
  role: "admin" | "owner" | "member"
  avatarUrl?: string
}

export function ViewModeProvider({
  children,
  user,
}: {
  children: React.ReactNode
  user?: UserProfile
}) {
  const [mode, setMode] = useState<ViewMode>("personal")
  const [loading, setIsLoading] = useState<boolean>(true)
  const [orgs, setOrgs] = useState<Organization[]>([])
  const [currentOrg, setCurrentOrg] = useState<Organization | null>(null)
  const fetchingRef = useRef(false)
  const orgsRef = useRef<Organization[]>([])

  const setLocalStorageMode = useCallback((newMode: ViewMode, orgId?: string) => {
    localStorage.setItem("viewMode", newMode)
    if (newMode === "organization" && orgId) {
      localStorage.setItem("currentOrganizationId", orgId)
    } else {
      localStorage.removeItem("currentOrganizationId")
    }
  }, [])

  const switchToMode = useCallback(
    async (newMode: ViewMode, orgId?: string, fetchedOrgs?: Organization[]) => {
      if (!user?.sub) return

      const finalOrgs = fetchedOrgs || orgsRef.current
      setLocalStorageMode(newMode, orgId)

      if (newMode === "organization" && orgId) {
        const org = finalOrgs.find(o => o.id === orgId)
        if (org) {
          setMode("organization")
          setCurrentOrg(org)
        } else {
          setMode("personal")
          setCurrentOrg(null)
        }
      } else {
        setMode("personal")
        setCurrentOrg(null)
      }
    },
    [user?.sub, setLocalStorageMode],
  )

  useEffect(() => {
    if (!user?.sub) {
      setIsLoading(false)
      return
    }
    if (fetchingRef.current) return
    fetchingRef.current = true

    setIsLoading(true)
    getUserOrganizations(user.sub)
      .then(result => {
        if (result.success && result.organizations) {
          setOrgs(result.organizations)
          orgsRef.current = result.organizations

          const savedMode = localStorage.getItem("viewMode") as ViewMode
          const savedOrgId = localStorage.getItem("currentOrganizationId")

          if (savedMode === "organization" && savedOrgId) {
            switchToMode("organization", savedOrgId, result.organizations)
          } else {
            switchToMode("personal", undefined, result.organizations)
          }
        }
      })
      .catch(error => console.error("Error fetching organizations:", error))
      .finally(() => {
        setIsLoading(false)
        fetchingRef.current = false
      })
  }, [user?.sub, switchToMode])

  const contextValue = useMemo(
    () => ({ mode, orgs, loading, currentOrg, switchToMode }),
    [mode, orgs, loading, currentOrg, switchToMode],
  )

  return <ViewModeContext.Provider value={contextValue}>{children}</ViewModeContext.Provider>
}

export function useViewMode() {
  const context = useContext(ViewModeContext)
  if (!context) {
    throw new Error("useViewMode must be used within a ViewModeProvider")
  }
  return context
}
