"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 { getBiddingsColumns } from "./biddings-table-columns"
import { getBiddings, getBiddingStatusCounts } from "@/lib/bidding/service"
import { BiddingListItem } from "@/db/schema"
import { BiddingsTableToolbarActions } from "./biddings-table-toolbar-actions"
import {
    biddingStatusLabels,
    contractTypeLabels,
    biddingTypeLabels
} from "@/db/schema"
import { EditBiddingSheet } from "./edit-bidding-sheet"
import { SpecificationMeetingDialog, PrDocumentsDialog } from "./bidding-detail-dialogs"


interface BiddingsTableProps {
    promises: Promise<
        [
            Awaited<ReturnType<typeof getBiddings>>,
            Awaited<ReturnType<typeof getBiddingStatusCounts>>
        ]
    >
}

export function BiddingsTable({ promises }: BiddingsTableProps) {
    const [{ data, pageCount }, statusCounts] = React.use(promises)
    const [isCompact, setIsCompact] = React.useState<boolean>(false)
    const [specMeetingDialogOpen, setSpecMeetingDialogOpen] = React.useState(false)
    const [prDocumentsDialogOpen, setPrDocumentsDialogOpen] = React.useState(false)
    const [selectedBidding, setSelectedBidding] = React.useState<BiddingListItem | null>(null)

    console.log(data,"data")

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

    const router = useRouter()

    const columns = React.useMemo(
        () => getBiddingsColumns({ setRowAction }),
        [setRowAction]
    )

    // rowAction 변경 감지하여 해당 다이얼로그 열기
    React.useEffect(() => {
        if (rowAction) {
            setSelectedBidding(rowAction.row.original)

            switch (rowAction.type) {
                case "view":
                    // 상세 페이지로 이동
                    router.push(`/evcp/bid/${rowAction.row.original.id}`)
                    break
                case "update":
                    // EditBiddingSheet는 아래에서 별도로 처리
                    break
                case "specification_meeting":
                    setSpecMeetingDialogOpen(true)
                    break
                case "pr_documents":
                    setPrDocumentsDialogOpen(true)
                    break
                // 기존 다른 액션들은 그대로 유지
                default:
                    break
            }
        }
    }, [rowAction])

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

    const advancedFilterFields: DataTableAdvancedFilterField<BiddingListItem>[] = [
        { id: "title", label: "입찰명", type: "text" },
        { id: "biddingNumber", label: "입찰번호", type: "text" },
        { id: "projectName", label: "프로젝트명", type: "text" },
        { id: "managerName", label: "담당자", type: "text" },
        {
            id: "status",
            label: "입찰상태",
            type: "multi-select",
            options: Object.entries(biddingStatusLabels).map(([value, label]) => ({
                label,
                value,
                count: statusCounts[value] || 0,
            })),
        },
        {
            id: "contractType",
            label: "계약구분",
            type: "select",
            options: Object.entries(contractTypeLabels).map(([value, label]) => ({
                label,
                value,
            })),
        },
        {
            id: "biddingType",
            label: "입찰유형",
            type: "select",
            options: Object.entries(biddingTypeLabels).map(([value, label]) => ({
                label,
                value,
            })),
        },
        { id: "createdAt", label: "등록일", type: "date" },
        { id: "updatedAt", label: "수정일", 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,
    })

    const handleCompactChange = React.useCallback((compact: boolean) => {
        setIsCompact(compact)
    }, [])


    const handleSpecMeetingDialogClose = React.useCallback(() => {
        setSpecMeetingDialogOpen(false)
        setRowAction(null)
        setSelectedBidding(null)
    }, [])

    const handlePrDocumentsDialogClose = React.useCallback(() => {
        setPrDocumentsDialogOpen(false)
        setRowAction(null)
        setSelectedBidding(null)
    }, [])


    return (
        <>
            <DataTable
                table={table}
                compact={isCompact}
            >
                <DataTableAdvancedToolbar
                    table={table}
                    filterFields={advancedFilterFields}
                    shallow={false}
                    enableCompactToggle={true}
                    compactStorageKey="biddingsTableCompact"
                    onCompactChange={handleCompactChange}
                >
                    <BiddingsTableToolbarActions table={table} />
                </DataTableAdvancedToolbar>
            </DataTable>

            <EditBiddingSheet
                open={rowAction?.type === "update"}
                onOpenChange={() => setRowAction(null)}
                bidding={rowAction?.row.original}
                onSuccess={() => router.refresh()}
            />

            {/* 사양설명회 다이얼로그 */}
            <SpecificationMeetingDialog
                open={specMeetingDialogOpen}
                onOpenChange={handleSpecMeetingDialogClose}
                bidding={selectedBidding}
            />

            {/* PR 문서 다이얼로그 */}
            <PrDocumentsDialog
                open={prDocumentsDialogOpen}
                onOpenChange={handlePrDocumentsDialogClose}
                bidding={selectedBidding}
            />
        </>

    )
} 