"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
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 { getColumns } from "./tbe-table-columns"
import { vendors } from "@/db/schema/vendors"
import { CommentSheet, TbeComment } from "@/lib/rfqs-tech/tbe-table/comments-sheet"
import { VendorWithTbeFields } from "@/config/vendorTbeColumnsConfig"
import { TBEFileDialog } from "@/lib/rfqs-tech/tbe-table/file-dialog"
import { fetchRfqAttachmentsbyCommentId, getAllTBE } from "@/lib/rfqs-tech/service"
import { VendorsTableToolbarActions } from "./tbe-table-toolbar-actions"
import { TbeResultDialog } from "@/lib/rfqs-tech/tbe-table/tbe-result-dialog"
import { toast } from "sonner"
import { VendorContactsDialog } from "@/lib/rfqs-tech/tbe-table/vendor-contact-dialog"
import { InviteVendorsDialog } from "@/lib/rfqs-tech/tbe-table/invite-vendors-dialog"

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

export function AllTbeTable({ promises }: VendorsTableProps) {
  const router = useRouter()

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

  // 벤더별로 데이터 그룹화
  const data = React.useMemo(() => {
    const vendorMap = new Map<number, VendorWithTbeFields>()
    
    rawData.forEach((item) => {
      const vendorId = item.vendorId
      
      if (vendorMap.has(vendorId)) {
        // 기존 벤더 데이터가 있으면 파일과 댓글을 합침
        const existing = vendorMap.get(vendorId)!
        
        // 파일 합치기 (중복 제거)
        const existingFileIds = new Set(existing.files.map(f => f.id))
        const newFiles = item.files.filter(f => !existingFileIds.has(f.id))
        existing.files = [...existing.files, ...newFiles]
        
        // 댓글 합치기 (중복 제거)
        const existingCommentIds = new Set(existing.comments.map(c => c.id))
        const newComments = item.comments.filter(c => !existingCommentIds.has(c.id))
        existing.comments = [...existing.comments, ...newComments]
        
      } else {
        // 새로운 벤더 데이터 추가
        vendorMap.set(vendorId, { 
          ...item, 
          vendorResponseId: item.id,
          technicalResponseId: item.id,
          rfqId: item.rfqId
        })
      }
    })
    
    return Array.from(vendorMap.values())
  }, [rawData])

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorWithTbeFields> | null>(null)

  // 댓글 시트 관련 state
  const [initialComments, setInitialComments] = React.useState<TbeComment[]>([])
  const [isLoadingComments, setIsLoadingComments] = React.useState(false)

  const [commentSheetOpen, setCommentSheetOpen] = React.useState(false)
  const [selectedVendorIdForComments, setSelectedVendorIdForComments] = React.useState<number | null>(null)
  const [selectedRfqIdForComments, setSelectedRfqIdForComments] = React.useState<number | null>(null)

  // 파일 다이얼로그 관련 state
  const [isFileDialogOpen, setIsFileDialogOpen] = React.useState(false)
  const [selectedVendorIdForFiles, setSelectedVendorIdForFiles] = React.useState<number | null>(null)
  const [selectedTbeIdForFiles, setSelectedTbeIdForFiles] = React.useState<number | null>(null)
  const [selectedRfqIdForFiles, setSelectedRfqIdForFiles] = React.useState<number | null>(null)

  const [isContactDialogOpen, setIsContactDialogOpen] = React.useState(false)
  const [selectedVendor, setSelectedVendor] = React.useState<VendorWithTbeFields | null>(null)
  const [selectedVendorId, setSelectedVendorId] = React.useState<number | null>(null)

  // 테이블 리프레시용
  const handleRefresh = React.useCallback(() => {
    router.refresh();
  }, [router]);

  // -----------------------------------------------------------
  // 특정 action이 설정될 때마다 실행되는 effect
  // -----------------------------------------------------------
  React.useEffect(() => {
    if (!rowAction) return

    if (rowAction.type === "comments") {
      openCommentSheet(
        rowAction.row.original.vendorId ?? 0,
        rowAction.row.original.rfqId ?? 0,
      )
    } else if (rowAction.type === "files") {
      openFilesDialog(
        rowAction.row.original.tbeId ?? 0,
        rowAction.row.original.vendorId ?? 0,
        rowAction.row.original.rfqId ?? 0,
      )
    } else if (rowAction.type === "invite") {
      // 선택된 row 정보 로그 출력
      const selectedRows = table.getSelectedRowModel().rows
      console.log("선택된 Row 정보:", {
        selectedRows: selectedRows.map(row => ({
          rfqId: row.original.rfqId,
          vendorId: row.original.vendorId,
          vendorName: row.original.vendorName,
          전체데이터: row.original
        })),
        총선택수: selectedRows.length
      })
      
      // 선택된 벤더들의 RFQ ID가 모두 동일한지 체크
      const rfqIds = new Set(selectedRows.map(row => row.original.rfqId))
      
      if (rfqIds.size > 1) {
        toast.error("동일한 rfq에 대해 초대가 가능합니다")
        setRowAction(null)
        return
      }

      // 선택된 첫 번째 row의 rfqId 사용
      const selectedRfqId = selectedRows[0]?.original.rfqId
      console.log("사용될 RFQ ID:", selectedRfqId)
    }
  }, [rowAction])

  // -----------------------------------------------------------
  // 댓글 시트 열기
  // -----------------------------------------------------------
  async function openCommentSheet(vendorId: number, rfqId: number) {
    setInitialComments([])
    setIsLoadingComments(true)
    const comments = rowAction?.row.original.comments
    try {
      if (comments && comments.length > 0) {
        const commentWithAttachments: TbeComment[] = await Promise.all(
          comments.map(async (c) => {
            const attachments = await fetchRfqAttachmentsbyCommentId(c.id)
            return {
              ...c,
              commentedBy: 1, // DB나 API 응답에 있다고 가정
              attachments,
            }
          })
        )
        setInitialComments(commentWithAttachments)
      }

      setSelectedVendorIdForComments(vendorId)
      setSelectedRfqIdForComments(rfqId)
      setCommentSheetOpen(true)
    } catch (error) {
      console.error("Error loading comments:", error)
      toast.error("Failed to load comments")
    } finally {
      // End loading regardless of success/failure
      setIsLoadingComments(false)
    }
  }

  // -----------------------------------------------------------
  // 파일 다이얼로그 열기
  // -----------------------------------------------------------
  const openFilesDialog = (tbeId: number, vendorId: number, rfqId: number) => {
    setSelectedTbeIdForFiles(tbeId)
    setSelectedVendorIdForFiles(vendorId)
    setSelectedRfqIdForFiles(rfqId)
    setIsFileDialogOpen(true)
  }

  const openVendorContactsDialog = (vendorId: number, vendor: VendorWithTbeFields) => {
    setSelectedVendorId(vendorId)
    setSelectedVendor(vendor)
    setIsContactDialogOpen(true)
  }


  // -----------------------------------------------------------
  // 테이블 컬럼
  // -----------------------------------------------------------
  const columns = React.useMemo(
    () =>
      getColumns({
        setRowAction,
        router,
        openCommentSheet,  // 필요하면 직접 호출 가능
        openFilesDialog,
        openVendorContactsDialog,
      }),
    [setRowAction, router]
  )

  // -----------------------------------------------------------
  // 필터 필드
  // -----------------------------------------------------------
  const filterFields: DataTableFilterField<VendorWithTbeFields>[] = [
    // 예: 표준 필터
  ]
  const advancedFilterFields: DataTableAdvancedFilterField<VendorWithTbeFields>[] = [
    { id: "vendorName", label: "Vendor Name", type: "text" },
    { id: "vendorCode", label: "Vendor Code", type: "text" },
    { id: "email", label: "Email", type: "text" },
    { id: "country", label: "Country", type: "text" },
    {
      id: "vendorStatus",
      label: "Vendor Status",
      type: "multi-select",
      options: vendors.status.enumValues.map((status) => ({
        label: toSentenceCase(status),
        value: status,
      })),
    },
    { id: "rfqVendorUpdated", label: "Updated at", type: "date" },
  ]

  // -----------------------------------------------------------
  // 테이블 생성 훅
  // -----------------------------------------------------------
  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "rfqVendorUpdated", desc: true }],
      columnPinning: { right: ["files", "comments"] },
    },
    getRowId: (originalRow) => (`${originalRow.id}${originalRow.rfqId}`),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <VendorsTableToolbarActions 
            table={table} 
            rfqId={table.getSelectedRowModel().rows[0]?.original.rfqId ?? 0} 
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 댓글 시트 */}
      <CommentSheet
        currentUserId={1}
        open={commentSheetOpen}
        tbeId={selectedTbeIdForFiles ?? 0}
        onOpenChange={setCommentSheetOpen}
        vendorId={selectedVendorIdForComments ?? 0}
        rfqId={selectedRfqIdForComments ?? 0}
        isLoading={isLoadingComments}
        initialComments={initialComments}
      />

      {/* 파일 업로드/다운로드 다이얼로그 */}
      <TBEFileDialog
        isOpen={isFileDialogOpen}
        onOpenChange={setIsFileDialogOpen}
        tbeId={selectedTbeIdForFiles ?? 0}
        vendorId={selectedVendorIdForFiles ?? 0}
        rfqId={selectedRfqIdForFiles ?? 0}
        onRefresh={handleRefresh}
      />

      <TbeResultDialog
        open={rowAction?.type === "tbeResult"}
        onOpenChange={() => setRowAction(null)}
        tbe={rowAction?.row.original ?? null}
      />

      <VendorContactsDialog
        isOpen={isContactDialogOpen}
        onOpenChange={setIsContactDialogOpen}
        vendorId={selectedVendorId}
        vendor={selectedVendor}
      />
      
    </>
  )
}