'use client'

import { useState, useEffect } from 'react'
import { createClient } from '@/lib/supabase/client'

interface MasterDataValue {
  id: string
  code: string
  label: string
  sort_order: number
}

const cache = new Map<string, MasterDataValue[]>()

export function useMasterDataValues(typeCode: string): {
  values: MasterDataValue[]
  loading: boolean
} {
  const [values, setValues] = useState<MasterDataValue[]>(cache.get(typeCode) ?? [])
  const [loading, setLoading] = useState(!cache.has(typeCode))

  useEffect(() => {
    if (cache.has(typeCode)) return
    const supabase = createClient()
    supabase
      .from('master_data_values')
      .select('id, code, label, sort_order, master_data_types!inner(code)')
      .eq('master_data_types.code', typeCode)
      .eq('is_active', true)
      .eq('is_hidden', false)
      .order('sort_order')
      .then(({ data }) => {
        const vals = (data ?? []).map(row => ({
          id: row.id as string,
          code: row.code as string,
          label: row.label as string,
          sort_order: row.sort_order as number,
        }))
        cache.set(typeCode, vals)
        setValues(vals)
        setLoading(false)
      })
  }, [typeCode])

  return { values, loading }
}
