"use client"

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

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 "./investigation-table-columns"
import { getVendorsInvestigation } from "../service"
import { VendorsTableToolbarActions } from "./investigation-table-toolbar-actions"
import { VendorInvestigationsViewWithContacts } from "@/config/vendorInvestigationsColumnsConfig"
import { UpdateVendorInvestigationSheet } from "./update-investigation-sheet"
import { VendorDetailsDialog } from "./vendor-details-dialog"

interface VendorsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getVendorsInvestigation>>,
    ]
  >
}

export function VendorsInvestigationTable({ promises }: VendorsTableProps) {
  const { featureFlags } = useFeatureFlags()
  
  // Get data from Suspense
  const [rawResponse] = React.use(promises)
  
  // Transform the data to match the expected types (simplified)
  const transformedData: VendorInvestigationsViewWithContacts[] = React.useMemo(() => {
    return rawResponse.data.map(item => {
      // Add id field for backward compatibility (maps to investigationId)
      return {
        ...item,
        id: item.investigationId, // Map investigationId to id for backward compatibility
      } as VendorInvestigationsViewWithContacts
    })
  }, [rawResponse.data])

  
  const pageCount = rawResponse.pageCount

  // Add state for row actions
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorInvestigationsViewWithContacts> | null>(null)
  
  // Add state for vendor details dialog
  const [vendorDetailsOpen, setVendorDetailsOpen] = React.useState(false)
  const [selectedVendorId, setSelectedVendorId] = React.useState<number | null>(null)
  
  // Create handler for opening vendor details modal
  const openVendorDetailsModal = React.useCallback((vendorId: number) => {
    setSelectedVendorId(vendorId)
    setVendorDetailsOpen(true)
  }, [])
  
  // Get router
  const router = useRouter()
  
  // Call getColumns() with required functions (simplified)
  const columns = React.useMemo(
    () => getColumns({ 
      setRowAction,
      openVendorDetailsModal
    }),
    [setRowAction, openVendorDetailsModal]
  )
  
  // 기본 필터 필드들
  const filterFields: DataTableFilterField<VendorInvestigationsViewWithContacts>[] = [
     { id: "vendorCode", label: "협력사 코드" },
     { id: "vendorName", label: "협력사명" },
     { id: "investigationStatus", label: "실사 상태" },
  ]
  
  // 고급 필터 필드들
  const advancedFilterFields: DataTableAdvancedFilterField<VendorInvestigationsViewWithContacts>[] = [
    // 협력업체 필터
    { id: "vendorName", label: "협력사명", type: "text" },
    { id: "vendorCode", label: "협력사 코드", type: "text" },
    
    // 실사 상태 필터
    { 
      id: "investigationStatus", 
      label: "실사 상태", 
      type: "select",
      options: [
        { label: "계획됨", value: "PLANNED" },
        { label: "진행 중", value: "IN_PROGRESS" },
        { label: "완료됨", value: "COMPLETED" },
        { label: "취소됨", value: "CANCELED" },
      ]
    },
    { 
      id: "evaluationType", 
      label: "평가 유형", 
      type: "select",
      options: [
        { label: "실사의뢰평가", value: "SITE_AUDIT" },
        { label: "QM자체평가", value: "QM_SELF_AUDIT" },
      ]
    },
    { 
      id: "evaluationResult", 
      label: "평가 결과", 
      type: "select",
      options: [
        { label: "승인", value: "APPROVED" },
        { label: "보완", value: "SUPPLEMENT" },
        { label: "불가", value: "REJECTED" },
      ]
    },
    
    // 점수 필터
    { id: "evaluationScore", label: "평가 점수", type: "number" },
    
    // 담당자 필터
    { id: "requesterName", label: "의뢰자", type: "text" },
    { id: "qmManagerName", label: "QM 담당자", type: "text" },
    
    // 첨부파일 필터
    { 
      id: "hasAttachments", 
      label: "첨부파일 유무", 
      type: "select",
      options: [
        { label: "첨부파일 있음", value: "true" },
        { label: "첨부파일 없음", value: "false" },
      ]
    },
    
    // 주요 날짜 필터
    { id: "forecastedAt", label: "실사 예정일", type: "date" },
    { id: "requestedAt", label: "실사 의뢰일", type: "date" },
    { id: "confirmedAt", label: "실사 확정일", type: "date" },
    { id: "completedAt", label: "실제 실사일", type: "date" },
    
    // 메모 필터
    { id: "investigationNotes", label: "QM 의견", type: "text" },
  ]
  
  // 데이터 테이블 초기화
  const { table } = useDataTable({
    data: transformedData,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
      columnVisibility: {
        // 자주 사용하지 않는 컬럼들은 기본적으로 숨김
        // investigationAddress: false,
        // investigationMethod: false,
        // requestedAt: false,
        // confirmedAt: false,
      }
    },
    getRowId: (originalRow) => String(originalRow.investigationId ?? originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })
  
  return (
    <>
      <DataTable
        table={table}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <VendorsTableToolbarActions table={table} />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* Update Investigation Sheet */}
      <UpdateVendorInvestigationSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        investigation={rowAction?.row.original ?? null}
      />
      
      {/* Vendor Details Dialog */}
      <VendorDetailsDialog
        open={vendorDetailsOpen}
        onOpenChange={setVendorDetailsOpen}
        vendorId={selectedVendorId}
      />
    </>
  )
}