'use client'

import { useState, useEffect, useCallback } from 'react'
import { dbOperations } from './db'
import type { Workspace, NoteFile, EditorState } from './types'

/**
 * Hook for managing the workspace (auto-created per API)
 */
export function useWorkspace(apiSpecUrl: string | null, apiName: string = 'API Notes') {
  const [workspace, setWorkspace] = useState<Workspace | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    if (!apiSpecUrl) {
      setWorkspace(null)
      setLoading(false)
      return
    }

    const loadWorkspace = async () => {
      try {
        setLoading(true)
        const ws = await dbOperations.getOrCreateWorkspace(apiSpecUrl, `${apiName} Notes`)
        setWorkspace(ws)
        setError(null)
      } catch (err) {
        setError(err instanceof Error ? err : new Error('Failed to load workspace'))
      } finally {
        setLoading(false)
      }
    }

    loadWorkspace()
  }, [apiSpecUrl, apiName])

  const clearWorkspace = useCallback(async () => {
    if (!workspace) return
    await dbOperations.clearWorkspace(workspace.id)
  }, [workspace])

  return {
    workspace,
    loading,
    error,
    clearWorkspace,
    workspaceId: workspace?.id || null,
  }
}

/**
 * Hook for managing notes/files in the workspace
 */
export function useNotes(workspaceId: string | null) {
  const [notes, setNotes] = useState<NoteFile[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  const loadNotes = useCallback(async () => {
    if (!workspaceId) {
      setNotes([])
      setLoading(false)
      return
    }

    try {
      setLoading(true)
      const list = await dbOperations.listNotes(workspaceId)
      setNotes(list)
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err : new Error('Failed to load notes'))
    } finally {
      setLoading(false)
    }
  }, [workspaceId])

  useEffect(() => {
    loadNotes()
  }, [loadNotes])

  const createNote = useCallback(async (path: string, content: string = ''): Promise<NoteFile | null> => {
    if (!workspaceId) return null
    
    const note = await dbOperations.createNote(workspaceId, path, content)
    setNotes(prev => [...prev, note])
    return note
  }, [workspaceId])

  const readNote = useCallback(async (path: string): Promise<string> => {
    if (!workspaceId) return ''
    
    const note = await dbOperations.getNote(workspaceId, path)
    return note?.content || ''
  }, [workspaceId])

  const updateNote = useCallback(async (path: string, content: string): Promise<void> => {
    if (!workspaceId) return
    
    await dbOperations.updateNote(workspaceId, path, content)
    setNotes(prev => prev.map(n => 
      n.path === path 
        ? { ...n, content, updatedAt: new Date() }
        : n
    ))
  }, [workspaceId])

  const deleteNote = useCallback(async (path: string): Promise<void> => {
    if (!workspaceId) return
    
    await dbOperations.deleteNote(workspaceId, path)
    setNotes(prev => prev.filter(n => n.path !== path))
  }, [workspaceId])

  const renameNote = useCallback(async (oldPath: string, newPath: string): Promise<void> => {
    if (!workspaceId) return
    
    await dbOperations.renameNote(workspaceId, oldPath, newPath)
    setNotes(prev => prev.map(n => 
      n.path === oldPath 
        ? { ...n, path: newPath, updatedAt: new Date() }
        : n
    ))
  }, [workspaceId])

  const deleteAllNotes = useCallback(async (): Promise<void> => {
    if (!workspaceId) return
    
    await dbOperations.clearWorkspace(workspaceId)
    setNotes([])
  }, [workspaceId])

  return {
    notes,
    loading,
    error,
    createNote,
    readNote,
    updateNote,
    deleteNote,
    deleteAllNotes,
    renameNote,
    refresh: loadNotes,
  }
}

/**
 * Hook for managing editor state (tabs, active file, etc.)
 */
export function useEditorState(workspaceId: string | null) {
  const [state, setState] = useState<EditorState | null>(null)

  // Load saved state
  useEffect(() => {
    if (!workspaceId) {
      setState(null)
      return
    }

    const loadState = async () => {
      const saved = await dbOperations.getEditorState(workspaceId)
      if (saved) {
        setState(saved)
      } else {
        // Initialize new state
        setState({
          workspaceId,
          openTabs: [],
          activeTab: null,
          cursorPositions: {},
          scrollPositions: {},
        })
      }
    }

    loadState()
  }, [workspaceId])

  // Save state when it changes
  useEffect(() => {
    if (state && workspaceId) {
      dbOperations.saveEditorState(state)
    }
  }, [state, workspaceId])

  const openTab = useCallback(async (path: string) => {
    setState(prev => {
      if (!prev) return prev
      
      const newTabs = prev.openTabs.includes(path)
        ? prev.openTabs
        : [...prev.openTabs, path]
      
      return {
        ...prev,
        openTabs: newTabs,
        activeTab: path,
      }
    })
  }, [])

  const closeTab = useCallback((path: string) => {
    setState(prev => {
      if (!prev) return prev
      
      const newTabs = prev.openTabs.filter(t => t !== path)
      const newActive = prev.activeTab === path
        ? newTabs[newTabs.length - 1] || null
        : prev.activeTab
      
      return {
        ...prev,
        openTabs: newTabs,
        activeTab: newActive,
      }
    })
  }, [])

  const setActiveTab = useCallback((path: string) => {
    setState(prev => {
      if (!prev) return prev
      return { ...prev, activeTab: path }
    })
  }, [])

  const saveCursorPosition = useCallback((path: string, line: number, column: number) => {
    setState(prev => {
      if (!prev) return prev
      return {
        ...prev,
        cursorPositions: {
          ...prev.cursorPositions,
          [path]: { line, column },
        },
      }
    })
  }, [])

  const clearAllTabs = useCallback(() => {
    setState(prev => {
      if (!prev) return prev
      return {
        ...prev,
        openTabs: [],
        activeTab: null,
        cursorPositions: {},
        scrollPositions: {},
      }
    })
  }, [])

  return {
    state,
    openTab,
    closeTab,
    setActiveTab,
    saveCursorPosition,
    clearAllTabs,
  }
}

// Re-export types and helpers
export type { Workspace, NoteFile, EditorState } from './types'
export { getFileType, getMonacoLanguage, supportsPreview } from './types'
export { getWorkspaceId } from './db'
