"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 { Button } from "@/components/ui/button"
import { Loader2 } from "lucide-react"
import { toast } from "sonner"

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 { getBiddingsReceiveColumns } from "./biddings-receive-columns"
import { getBiddingsForReceive } from "@/lib/bidding/service"
import {
    biddingStatusLabels,
    contractTypeLabels,
} from "@/db/schema"
// import { SpecificationMeetingDialog, PrDocumentsDialog } from "../list/bidding-detail-dialogs"
import { openBiddingAction, earlyOpenBiddingAction } from "@/lib/bidding/actions"

type BiddingReceiveItem = {
  id: number
  biddingNumber: string
  originalBiddingNumber: string | null
  title: string
  status: string
  contractType: string
  prNumber: string | null
  submissionStartDate: Date | null
  submissionEndDate: Date | null
  bidPicName: string | null
  supplyPicName: string | null
  createdBy: string | null
  createdAt: Date | null
  updatedAt: Date | null

  // 참여 현황
  participantExpected: number
  participantParticipated: number
  participantDeclined: number
  participantPending: number

  // 개찰 정보
  openedAt: Date | null
  openedBy: string | null
}

interface BiddingsReceiveTableProps {
    promises: Promise<
        [
            Awaited<ReturnType<typeof getBiddingsForReceive>>
        ]
    >
}

export function BiddingsReceiveTable({ promises }: BiddingsReceiveTableProps) {
    const [biddingsResult] = 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<BiddingReceiveItem | null>(null)

    const [rowAction, setRowAction] = React.useState<DataTableRowAction<BiddingReceiveItem> | null>(null)
    const [isOpeningBidding, setIsOpeningBidding] = React.useState(false)
    const [isEarlyOpeningBidding, setIsEarlyOpeningBidding] = React.useState(false)

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

    const columns = React.useMemo(
        () => getBiddingsReceiveColumns({ 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
                default:
                    break
            }
        }
    }, [rowAction])

    const filterFields: DataTableFilterField<BiddingReceiveItem>[] = [
        {
            id: "biddingNumber",
            label: "입찰번호",
            placeholder: "입찰번호를 입력하세요",
        },
        {
            id: "prNumber",
            label: "P/R번호",
            placeholder: "P/R번호를 입력하세요",
        },
        {
            id: "title",
            label: "입찰명",
            placeholder: "입찰명을 입력하세요",
        },
    ]

    const advancedFilterFields: DataTableAdvancedFilterField<BiddingReceiveItem>[] = [
        { id: "title", label: "입찰명", type: "text" },
        { id: "biddingNumber", label: "입찰번호", type: "text" },
        { id: "bidPicName", label: "입찰담당자", type: "text" },
        {
            id: "status",
            label: "진행상태",
            type: "multi-select",
            options: Object.entries(biddingStatusLabels).map(([value, label]) => ({
                label,
                value,
            })),
        },
        {
            id: "contractType",
            label: "계약구분",
            type: "select",
            options: Object.entries(contractTypeLabels).map(([value, label]) => ({
                label,
                value,
            })),
        },
        { id: "createdAt", label: "등록일", type: "date" },
        { id: "submissionStartDate", label: "제출시작일", type: "date" },
        { id: "submissionEndDate", label: "제출마감일", type: "date" },
    ]

    const { table } = useDataTable({
        data,
        columns,
        pageCount,
        filterFields,
        enablePinning: true,
        enableAdvancedFilter: true,
        enableRowSelection: 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)
    // }, [])

    // 선택된 행 가져오기
    const selectedRows = table.getFilteredSelectedRowModel().rows
    const selectedBiddingForAction = selectedRows.length > 0 ? selectedRows[0].original : null

    // 조기개찰 가능 여부 확인
    const canEarlyOpen = React.useMemo(() => {
        if (!selectedBiddingForAction) return false

        const now = new Date()
        const submissionEndDate = selectedBiddingForAction.submissionEndDate

        // 참여협력사가 1명 이상이어야 함
        if (selectedBiddingForAction.participantParticipated < 1) return false

        // 입찰서 제출기간 내여야 함
        if (!submissionEndDate || now > submissionEndDate) return false

        // 미제출 협력사가 0이어야 함
        if (selectedBiddingForAction.participantPending > 0) return false

        // 참여협력사 + 포기협력사 = 참여예정협력사 여야 함
        const participatedOrDeclined = selectedBiddingForAction.participantParticipated + selectedBiddingForAction.participantDeclined
        return participatedOrDeclined === selectedBiddingForAction.participantExpected
    }, [selectedBiddingForAction])

    // 개찰 가능 여부 확인
    const canOpen = React.useMemo(() => {
        if (!selectedBiddingForAction) return false

        // 참여협력사가 1명 이상이어야 함
        if (selectedBiddingForAction.participantParticipated < 1) return false

        const now = new Date()
        const submissionEndDate = selectedBiddingForAction.submissionEndDate

        // 입찰서 제출기간이 종료되어야 함
        return submissionEndDate && now > submissionEndDate
    }, [selectedBiddingForAction])

    const handleEarlyOpenBidding = React.useCallback(async () => {
        if (!selectedBiddingForAction) return

        setIsEarlyOpeningBidding(true)
        try {
            const result = await earlyOpenBiddingAction(selectedBiddingForAction.id)
            if (result.success) {
                toast.success("조기개찰이 완료되었습니다.")
                // 데이터 리프레시
                window.location.reload()
            } else {
                toast.error(result.message || "조기개찰에 실패했습니다.")
            }
        } catch (error) {
            toast.error("조기개찰 중 오류가 발생했습니다.")
        } finally {
            setIsEarlyOpeningBidding(false)
        }
    }, [selectedBiddingForAction])

    const handleOpenBidding = React.useCallback(async () => {
        if (!selectedBiddingForAction) return

        setIsOpeningBidding(true)
        try {
            const result = await openBiddingAction(selectedBiddingForAction.id)
            if (result.success) {
                toast.success("개찰이 완료되었습니다.")
                // 데이터 리프레시
                window.location.reload()
            } else {
                toast.error(result.message || "개찰에 실패했습니다.")
            }
        } catch (error) {
            toast.error("개찰 중 오류가 발생했습니다.")
        } finally {
            setIsOpeningBidding(false)
        }
    }, [selectedBiddingForAction])

    return (
        <>
            <DataTable
                table={table}
                compact={isCompact}
            >
                <DataTableAdvancedToolbar
                    table={table}
                    filterFields={advancedFilterFields}
                    shallow={false}
                    enableCompactToggle={true}
                    compactStorageKey="biddingsReceiveTableCompact"
                    onCompactChange={handleCompactChange}
                >
                    <div className="flex items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={handleEarlyOpenBidding}
                            disabled={!selectedBiddingForAction || !canEarlyOpen || isEarlyOpeningBidding}
                        >
                            {isEarlyOpeningBidding && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            조기개찰
                        </Button>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={handleOpenBidding}
                            disabled={!selectedBiddingForAction || isOpeningBidding}
                        >
                            {isOpeningBidding && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            개찰
                        </Button>
                    </div>
                </DataTableAdvancedToolbar>
            </DataTable>

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

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