"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { useSession } from "next-auth/react"
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 { BiddingListItemWithManagerCode } from "./biddings-table-columns"
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 [biddingsResult, statusCounts] = React.use(promises)

    // biddingsResult에서 data와 pageCount 추출
    const { data, pageCount } = biddingsResult

    const [isCompact, setIsCompact] = React.useState<boolean>(false)
    const [specMeetingDialogOpen, setSpecMeetingDialogOpen] = React.useState(false)
    const [prDocumentsDialogOpen, setPrDocumentsDialogOpen] = React.useState(false)
    const [selectedBidding, setSelectedBidding] = React.useState<BiddingListItemWithManagerCode | null>(null)

    console.log(data,"data")

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

    const router = useRouter()
    const { data: session } = useSession()

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

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

            switch (rowAction.type) {
                case "view":
                    // 상세 페이지로 이동 (info 페이지로)
                    router.push(`/evcp/bid/${rowAction.row.original.id}/info`)
                    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: "bidPicName", 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,
        enableMultiRowSelection: false,
        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>
            
            {/* 사양설명회 다이얼로그 */}
            <SpecificationMeetingDialog
                open={specMeetingDialogOpen}
                onOpenChange={handleSpecMeetingDialogClose}
                bidding={selectedBidding}
            />

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

        </>

    )
} 