"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { toSentenceCase } from "@/lib/utils"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { useFeatureFlags } from "./feature-flags-provider"
import { getColumns } from "./contact-table-columns"
import { getVendorContacts, deleteVendorContact } from "../service"
import { VendorContact, vendors } from "@/db/schema/vendors"
import { VendorsTableToolbarActions } from "./contact-table-toolbar-actions"
import { EditContactDialog } from "./edit-contact-dialog"
import { toast } from "sonner"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"

interface VendorsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getVendorContacts>>,
    ]
  >, 
  vendorId:number
}

export function VendorContactsTable({ promises , vendorId}: VendorsTableProps) {
  const { featureFlags } = useFeatureFlags()

  // Suspense로 받아온 데이터
  const [{ data, pageCount }] = React.use(promises)

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorContact> | null>(null)
  const [editDialogOpen, setEditDialogOpen] = React.useState(false)
  const [selectedContact, setSelectedContact] = React.useState<VendorContact | null>(null)
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
  const [isDeleting, setIsDeleting] = React.useState(false)

  // Edit 액션 처리
  React.useEffect(() => {
    if (rowAction?.type === "update") {
      setSelectedContact(rowAction.row.original)
      setEditDialogOpen(true)
      setRowAction(null)
    } else if (rowAction?.type === "delete") {
      setSelectedContact(rowAction.row.original)
      setDeleteDialogOpen(true)
      setRowAction(null)
    }
  }, [rowAction])

  // Delete 액션 처리 함수
  const handleDelete = React.useCallback(async () => {
    if (!selectedContact) return

    setIsDeleting(true)
    try {
      const result = await deleteVendorContact({
        id: selectedContact.id,
        vendorId: vendorId
      })

      if (result.success) {
        toast.success(result.message)
        // 페이지를 새로고침하거나 데이터를 다시 가져오기
        window.location.reload()
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      toast.error("Failed to delete contact")
      console.error("Error deleting contact:", error)
    } finally {
      setIsDeleting(false)
      setDeleteDialogOpen(false)
      setSelectedContact(null)
    }
  }, [selectedContact, vendorId])

  // 데이터 새로고침 함수
  const handleEditSuccess = React.useCallback(() => {
    // 페이지를 새로고침하거나 데이터를 다시 가져오기
    window.location.reload()
  }, [])

  // getColumns() 호출 시, router를 주입
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  const filterFields: DataTableFilterField<VendorContact>[] = [
    
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<VendorContact>[] = [
    { id: "contactName", label: "Contact Name", type: "text" },
    { id: "contactPosition", label: "Contact Position", type: "text" },
    { id: "contactEmail", label: "Contact Email", type: "text" },
    { id: "contactPhone", label: "Contact Phone", type: "text" },
    { id: "createdAt", label: "Created at", type: "date" },
    { id: "updatedAt", label: "Updated at", type: "date" },
  ]

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable
        table={table}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <VendorsTableToolbarActions table={table} vendorId={vendorId} />
        </DataTableAdvancedToolbar>
      </DataTable>

      <EditContactDialog
        contact={selectedContact}
        open={editDialogOpen}
        onOpenChange={setEditDialogOpen}
        onSuccess={handleEditSuccess}
      />

      {/* Delete 확인 다이얼로그 */}
      {selectedContact && (
        <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>연락처 삭제</DialogTitle>
              <DialogDescription>
                정말로 "{selectedContact.contactName}" 연락처를 삭제하시겠습니까?
                이 작업은 되돌릴 수 없습니다.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDeleteDialogOpen(false)}
                disabled={isDeleting}
              >
                취소
              </Button>
              <Button
                variant="destructive"
                onClick={handleDelete}
                disabled={isDeleting}
              >
                {isDeleting ? "삭제 중..." : "삭제"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </>
  )
}