"use client"

import React, { createContext, useContext, useEffect, useState, useCallback } from "react"
import {
  getPrivacyMode,
  updatePrivacyMode,
  checkCanUsePrivacyMode,
  getOrgPrivacyMode,
  updateOrgPrivacyMode,
  checkOrgCanUsePrivacyMode,
} from "./privacy-actions"
import { useViewMode } from "./ViewModeContext"

type PrivacyModeContextType = {
  isPrivacyMode: boolean
  isLoading: boolean
  canUsePrivacyMode: boolean
  canTogglePrivacyMode: boolean // For org: only admins can toggle
  togglePrivacyMode: () => void
  setPrivacyMode: (enabled: boolean) => void
  isOrgMode: boolean
}

const PrivacyModeContext = createContext<PrivacyModeContextType>({
  isPrivacyMode: false,
  isLoading: true,
  canUsePrivacyMode: false,
  canTogglePrivacyMode: false,
  togglePrivacyMode: () => {},
  setPrivacyMode: () => {},
  isOrgMode: false,
})

const STORAGE_KEY = "privacyMode"

interface PrivacyModeProviderProps {
  children: React.ReactNode
  userId?: string
  initialPrivacyMode?: boolean
  initialCanUsePrivacyMode?: boolean
}

export function PrivacyModeProvider({
  children,
  userId,
  initialPrivacyMode,
  initialCanUsePrivacyMode,
}: PrivacyModeProviderProps) {
  const hasInitialData = initialPrivacyMode !== undefined && initialCanUsePrivacyMode !== undefined
  const [isPrivacyMode, setIsPrivacyMode] = useState<boolean>(
    hasInitialData ? (initialCanUsePrivacyMode ? initialPrivacyMode : false) : false,
  )
  const [isLoading, setIsLoading] = useState(!hasInitialData)
  const [canUsePrivacyMode, setCanUsePrivacyMode] = useState(initialCanUsePrivacyMode ?? false)
  const { mode, currentOrg } = useViewMode()

  const isOrgMode = mode === "organization" && !!currentOrg
  const isOrgAdmin = isOrgMode && (currentOrg?.role === "admin" || currentOrg?.role === "owner")

  // Can toggle: personal mode (if paid) OR org mode (if admin and org has subscription)
  const canTogglePrivacyMode = isOrgMode ? isOrgAdmin && canUsePrivacyMode : canUsePrivacyMode

  // Track whether we've used initial data for the first personal-mode render
  const usedInitialDataRef = React.useRef(false)

  // Load saved preference from database
  useEffect(() => {
    const loadPrivacyMode = async () => {
      if (isOrgMode && currentOrg?.id) {
        // Organization mode - always fetch org-specific privacy settings
        setIsLoading(true)
        try {
          const [orgPrivacyMode, orgCanUse] = await Promise.all([
            getOrgPrivacyMode(currentOrg.id),
            checkOrgCanUsePrivacyMode(currentOrg.id),
          ])
          setCanUsePrivacyMode(orgCanUse)
          setIsPrivacyMode(orgCanUse ? orgPrivacyMode : false)
        } catch (error) {
          console.error("Error fetching org privacy mode:", error)
          setIsPrivacyMode(false)
          setCanUsePrivacyMode(false)
        }
        setIsLoading(false)
      } else if (userId) {
        // Personal mode - skip fetch if initial data was provided by the server
        if (hasInitialData && !usedInitialDataRef.current) {
          usedInitialDataRef.current = true
          // Sync localStorage with server-provided value
          try {
            const effectivePrivacyMode = initialCanUsePrivacyMode ? initialPrivacyMode : false
            localStorage.setItem(STORAGE_KEY, String(effectivePrivacyMode))
          } catch {
            // localStorage not available
          }
          return
        }

        setIsLoading(true)
        // First, load from localStorage for instant UI
        try {
          const saved = localStorage.getItem(STORAGE_KEY)
          if (saved !== null) {
            setIsPrivacyMode(saved === "true")
          }
        } catch {
          // localStorage not available
        }

        try {
          const [dbPrivacyMode, isPaid] = await Promise.all([
            getPrivacyMode(userId),
            checkCanUsePrivacyMode(userId),
          ])
          setCanUsePrivacyMode(isPaid)
          const effectivePrivacyMode = isPaid ? dbPrivacyMode : false
          setIsPrivacyMode(effectivePrivacyMode)
          // Sync localStorage with database value
          try {
            localStorage.setItem(STORAGE_KEY, String(effectivePrivacyMode))
          } catch {
            // localStorage not available
          }
        } catch (error) {
          console.error("Error fetching privacy mode from database:", error)
        }
        setIsLoading(false)
      }
    }

    loadPrivacyMode()
  }, [
    userId,
    isOrgMode,
    currentOrg?.id,
    hasInitialData,
    initialPrivacyMode,
    initialCanUsePrivacyMode,
  ])

  const updatePrivacyModeValue = useCallback(
    async (newValue: boolean) => {
      // Only allow enabling privacy mode if allowed
      if (newValue && !canUsePrivacyMode) {
        return
      }

      // In org mode, only admins can toggle
      if (isOrgMode && !isOrgAdmin) {
        return
      }

      setIsPrivacyMode(newValue)

      if (isOrgMode && currentOrg?.id && userId) {
        // Update organization privacy mode
        try {
          const result = await updateOrgPrivacyMode(userId, currentOrg.id, newValue)
          if (!result.success) {
            // Revert on failure
            setIsPrivacyMode(!newValue)
            console.error("Failed to update org privacy mode:", result.error)
          }
        } catch (error) {
          console.error("Error updating org privacy mode:", error)
          setIsPrivacyMode(!newValue)
        }
      } else if (userId) {
        // Update personal privacy mode
        try {
          localStorage.setItem(STORAGE_KEY, String(newValue))
        } catch {
          // localStorage not available
        }

        try {
          await updatePrivacyMode(userId, newValue)
        } catch (error) {
          console.error("Error updating privacy mode in database:", error)
        }
      }
    },
    [userId, canUsePrivacyMode, isOrgMode, isOrgAdmin, currentOrg?.id],
  )

  const togglePrivacyMode = useCallback(() => {
    updatePrivacyModeValue(!isPrivacyMode)
  }, [isPrivacyMode, updatePrivacyModeValue])

  const setPrivacyModeCallback = useCallback(
    (enabled: boolean) => {
      updatePrivacyModeValue(enabled)
    },
    [updatePrivacyModeValue],
  )

  return (
    <PrivacyModeContext.Provider
      value={{
        isPrivacyMode,
        isLoading,
        canUsePrivacyMode,
        canTogglePrivacyMode,
        togglePrivacyMode,
        setPrivacyMode: setPrivacyModeCallback,
        isOrgMode,
      }}
    >
      {children}
    </PrivacyModeContext.Provider>
  )
}

export function usePrivacyMode() {
  const context = useContext(PrivacyModeContext)
  if (!context) {
    throw new Error("usePrivacyMode must be used within a PrivacyModeProvider")
  }
  return context
}
