import { useMemo } from 'react'
import { isSupabaseConfigured } from '../lib/supabase'
import { useSupabaseTable, UseSupabaseTableOptions } from './useSupabaseTable'

/**
 * @ai-marker AUTO_SWITCH_DATA
 * Auto-switching data hook — uses Supabase when configured, falls back to
 * sample data when not configured OR when the live fetch errors (e.g. the
 * table does not exist yet), so the app never renders blank.
 *
 * Usage:
 * const { data, loading, error, isLive } = useData('posts', SAMPLE_POSTS);
 */
export function useData<T extends { id?: string | number }>(
  table: string,
  sampleData: T[],
  options?: Omit<UseSupabaseTableOptions, 'enabled'>
): {
  data: T[]
  loading: boolean
  error: string | null
  isLive: boolean
  add: (data: Omit<T, 'id' | 'created_at' | 'user_id'>) => Promise<string | null>
  update: (id: string, data: Partial<T>) => Promise<boolean>
  remove: (id: string) => Promise<boolean>
  refresh: () => void
} {
  const isLive = isSupabaseConfigured()

  const live = useSupabaseTable<T>(isLive ? table : '', { ...options, enabled: isLive })

  return useMemo(() => {
    if (!isLive) {
      return {
        data: sampleData,
        loading: false,
        error: null,
        isLive: false,
        add: async () => {
          console.warn('[useData] add() ignored: Supabase is not configured.')
          return null
        },
        update: async () => {
          console.warn('[useData] update() ignored: Supabase is not configured.')
          return false
        },
        remove: async () => {
          console.warn('[useData] remove() ignored: Supabase is not configured.')
          return false
        },
        refresh: () => {},
      }
    }

    // Fall back to sample data while the first fetch is loading or if the
    // live fetch errored (e.g. the table is missing) — never blank.
    const useSample = live.loading || !!live.error
    return {
      data: (useSample ? sampleData : (live.data as unknown as T[])),
      loading: live.loading,
      error: live.error,
      isLive: true,
      add: live.add,
      update: live.update,
      remove: live.remove,
      refresh: live.refresh,
    }
  }, [isLive, live, sampleData])
}
