// lib/tbe-last/table/tbe-last-table.tsx

"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { type DataTableAdvancedFilterField } 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 { getColumns } from "./tbe-last-table-columns"
import { TbeLastView } from "@/db/schema"
import { getAllTBELast, getTBESessionDetail } from "@/lib/tbe-last/service"
import { Button } from "@/components/ui/button"
import { Download, RefreshCw } from "lucide-react"
import { exportTableToExcel } from "@/lib/export"

// Import Dialogs and Sheets
import { SessionDetailDialog } from "./session-detail-dialog"
import { DocumentsSheet } from "./documents-sheet"
import { PrItemsDialog } from "./pr-items-dialog"
import { EvaluationDialog } from "./evaluation-dialog"

interface TbeLastTableProps {
  promises: Promise<[
    Awaited<ReturnType<typeof getAllTBELast>>,
  ]>
}

export function TbeLastTable({ promises }: TbeLastTableProps) {
  const router = useRouter()
  const [{ data, pageCount }] = React.use(promises)
  
  console.log(data,"data")

  // Dialog states
  const [sessionDetailOpen, setSessionDetailOpen] = React.useState(false)
  const [documentsOpen, setDocumentsOpen] = React.useState(false)
  const [prItemsOpen, setPrItemsOpen] = React.useState(false)
  const [evaluationOpen, setEvaluationOpen] = React.useState(false)
  
  const [selectedSessionId, setSelectedSessionId] = React.useState<number | null>(null)
  const [selectedRfqId, setSelectedRfqId] = React.useState<number | null>(null)
  const [selectedSession, setSelectedSession] = React.useState<TbeLastView | null>(null)
  const [sessionDetail, setSessionDetail] = React.useState<any>(null)
  const [isLoadingDetail, setIsLoadingDetail] = React.useState(false)
  
  // Load session detail when needed
  const loadSessionDetail = React.useCallback(async (sessionId: number) => {
    setIsLoadingDetail(true)
    try {
      const detail = await getTBESessionDetail(sessionId)
      setSessionDetail(detail)
    } catch (error) {
      console.error("Failed to load session detail:", error)
    } finally {
      setIsLoadingDetail(false)
    }
  }, [])
  
  // Handlers
  const handleOpenSessionDetail = React.useCallback((sessionId: number) => {
    setSelectedSessionId(sessionId)
    setSessionDetailOpen(true)
    loadSessionDetail(sessionId)
  }, [loadSessionDetail])
  
  const handleOpenDocuments = React.useCallback((sessionId: number) => {
    setSelectedSessionId(sessionId)
    setDocumentsOpen(true)
    loadSessionDetail(sessionId)
  }, [loadSessionDetail])
  
  const handleOpenPrItems = React.useCallback((rfqId: number) => {
    setSelectedRfqId(rfqId)
    setPrItemsOpen(true)
    loadSessionDetail(rfqId)
  }, [loadSessionDetail])
  
  const handleOpenEvaluation = React.useCallback((session: TbeLastView) => {
    setSelectedSession(session)
    setEvaluationOpen(true)
    loadSessionDetail(session.rfqId)

  }, [])
  
  const handleRefresh = React.useCallback(() => {
    router.refresh()
  }, [router])
  
  // Table columns
  const columns = React.useMemo(
    () =>
      getColumns({
        onOpenSessionDetail: handleOpenSessionDetail,
        onOpenDocuments: handleOpenDocuments,
        onOpenPrItems: handleOpenPrItems,
        onOpenEvaluation: handleOpenEvaluation,
      }),
    [handleOpenSessionDetail, handleOpenDocuments, handleOpenPrItems, handleOpenEvaluation]
  )
  
  // Filter fields
  const filterFields: DataTableAdvancedFilterField<TbeLastView>[] = [
    {
      id: "sessionStatus",
      label: "Status",
      type: "select",
      options: [
        { label: "준비중", value: "준비중" },
        { label: "진행중", value: "진행중" },
        { label: "검토중", value: "검토중" },
        { label: "보류", value: "보류" },
        { label: "완료", value: "완료" },
      ],
    },
    {
      id: "evaluationResult",
      label: "Result",
      type: "select",
      options: [
        { label: "Pass", value: "pass" },
        { label: "Conditional Pass", value: "conditional_pass" },
        { label: "Non-Pass", value: "non_pass" },
      ],
    },
  ]
  
  // Data table
  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["documents"] },
    },
    getRowId: (originalRow) => String(originalRow.tbeSessionId),
    shallow: false,
    clearOnDefault: true,
  })
  
  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={filterFields}
          shallow={false}
        >
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              className="gap-2"
            >
              <RefreshCw className="size-4" />
              <span>Refresh</span>
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() =>
                exportTableToExcel(table, {
                  filename: "tbe-sessions",
                  excludeColumns: ["select", "actions"],
                })
              }
              className="gap-2"
            >
              <Download className="size-4" />
              <span>Export</span>
            </Button>
          </div>
        </DataTableAdvancedToolbar>
      </DataTable>
      
      {/* Session Detail Dialog */}
      <SessionDetailDialog
        open={sessionDetailOpen}
        onOpenChange={setSessionDetailOpen}
        sessionDetail={sessionDetail}
        isLoading={isLoadingDetail}
      />
      
      {/* Documents Sheet */}
      <DocumentsSheet
        open={documentsOpen}
        onOpenChange={setDocumentsOpen}
        sessionDetail={sessionDetail}
        isLoading={isLoadingDetail}
      />
      
      {/* PR Items Dialog */}
      <PrItemsDialog
        open={prItemsOpen}
        onOpenChange={setPrItemsOpen}
        sessionDetail={sessionDetail}
        isLoading={isLoadingDetail}
      />
      
      {/* Evaluation Dialog */}
      <EvaluationDialog
        open={evaluationOpen}
        onOpenChange={setEvaluationOpen}
        selectedSession={selectedSession}
        sessionDetail={sessionDetail}

      />
    </>
  )
}