import { useEffect, useCallback, useRef } from 'react'
import { supabase } from '../auth/supabase.ts'
import { useAuth } from '../auth/AuthProvider.tsx'
import { migrateLegacyDocuments } from './migrateLegacy.ts'

export interface CloudDocument {
  id: string
  owner_id: string
  title: string
  folder_id: string | null
  is_favorite: boolean
  share_token: string | null
  share_permission: string | null
  created_at: string
  updated_at: string
}

/**
 * Hook to sync document metadata with Supabase.
 * Handles initial migration from localStorage and ongoing sync.
 */
export function useCloudSync() {
  const auth = useAuth()
  const migrationDone = useRef(false)

  // Run legacy migration on first login
  useEffect(() => {
    if (!auth.isAuthenticated || !auth.user || migrationDone.current) return
    migrationDone.current = true

    migrateLegacyDocuments(auth.user.id).then(count => {
      if (count > 0) {
        console.log(`Migrated ${count} documents to cloud`)
      }
    })
  }, [auth.isAuthenticated, auth.user])

  /** Fetch all documents for the current user */
  const fetchDocuments = useCallback(async (): Promise<CloudDocument[]> => {
    if (!supabase || !auth.user) return []

    const { data, error } = await supabase
      .from('documents')
      .select('*')
      .eq('owner_id', auth.user.id)
      .order('updated_at', { ascending: false })

    if (error) {
      console.error('Failed to fetch documents:', error)
      return []
    }

    return data ?? []
  }, [auth.user])

  /** Create a new document in the cloud */
  const createCloudDocument = useCallback(async (title: string): Promise<CloudDocument | null> => {
    if (!supabase || !auth.user) return null

    const { data, error } = await supabase
      .from('documents')
      .insert({
        owner_id: auth.user.id,
        title,
      })
      .select()
      .single()

    if (error) {
      console.error('Failed to create document:', error)
      return null
    }

    return data
  }, [auth.user])

  /** Update document metadata */
  const updateCloudDocument = useCallback(async (
    id: string,
    updates: Partial<Pick<CloudDocument, 'title' | 'folder_id' | 'is_favorite'>>,
  ): Promise<void> => {
    if (!supabase) return

    await supabase
      .from('documents')
      .update({ ...updates, updated_at: new Date().toISOString() })
      .eq('id', id)
  }, [])

  /** Delete a document */
  const deleteCloudDocument = useCallback(async (id: string): Promise<void> => {
    if (!supabase) return
    await supabase.from('documents').delete().eq('id', id)
  }, [])

  return {
    fetchDocuments,
    createCloudDocument,
    updateCloudDocument,
    deleteCloudDocument,
    isAuthenticated: auth.isAuthenticated,
  }
}
