'use client'

import * as React from "react"
import { ClientDataTable } from "@/components/client-data-table/data-table"
import { getColumns } from "./vendor-contact-table-column"
import { DataTableAdvancedFilterField } from "@/types/table"
import { Loader2 } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { getVendorContactsByVendorId } from "../../service"

export interface VendorData {
  id: number
  contactName: string
  contactPosition: string | null
  contactEmail: string
  contactPhone: string | null
  isPrimary: boolean | null
  createdAt: Date
  updatedAt: Date
}

interface VendorContactsTableProps {
  vendorId: number
}

export function VendorContactsTable({ vendorId }: VendorContactsTableProps) {
  const { toast } = useToast()
  
  const columns = React.useMemo(
    () => getColumns(),
    []
  )
  
  const [vendorContacts, setVendorContacts] = React.useState<VendorData[]>([])
  const [isLoading, setIsLoading] = React.useState(false)
  
  React.useEffect(() => {
    async function loadVendorContacts() {
      setIsLoading(true)
      try {
        const result = await getVendorContactsByVendorId(vendorId)
        if (result.success && result.data) {
          // undefined 체크 추가 및 타입 캐스팅
          setVendorContacts(result.data as VendorData[])
        } else {
          throw new Error(result.error || "Unknown error occurred")
        }
      } catch (error) {
        console.error("협력업체 연락처 로드 오류:", error)
        toast({
          title: "Error",
          description: "Failed to load vendor contacts",
          variant: "destructive",
        })
      } finally {
        setIsLoading(false)
      }
    }
    loadVendorContacts()
  }, [toast, vendorId])
  
  const advancedFilterFields: DataTableAdvancedFilterField<VendorData>[] = [
    { id: "contactName", label: "Contact Name", type: "text" },
    { id: "contactPosition", label: "Posiotion", type: "text" },
    { id: "contactEmail", label: "Email", type: "text" },
    { id: "contactPhone", label: "Phone", type: "text" },


  ]
   
  // If loading, show a flex container that fills the parent and centers the spinner
  if (isLoading) {
    return (
      <div className="flex h-full w-full items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    )
  }
  
  // Otherwise, show the table
  return (
    <ClientDataTable
      data={vendorContacts}
      columns={columns}
      advancedFilterFields={advancedFilterFields}
    >
    </ClientDataTable>
  )
}