"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 { getGeneralContractsColumns, GeneralContractListItem } from "./general-contracts-table-columns"
import { getGeneralContracts, getGeneralContractStatusCounts } from "@/lib/general-contracts/service"
import { GeneralContractsTableToolbarActions } from "./general-contracts-table-toolbar-actions"
import { GeneralContractUpdateSheet } from "./general-contract-update-sheet"
import { 
  GENERAL_EXECUTION_METHODS
} from "@/lib/general-contracts/types"

// 상태 라벨 매핑
const contractStatusLabels = {
  'Draft': '임시저장',
  'Request to Review': '조건검토요청',
  'Confirm to Review': '조건검토완료',
  'Contract Accept Request': '계약승인요청',
  'Complete the Contract': '계약체결',
  'Reject to Accept Contract': '계약승인거절',
  'Contract Delete': '계약폐기',
  'PCR Request': 'PCR요청',
  'VO Request': 'VO요청',
  'PCR Accept': 'PCR승인',
  'PCR Reject': 'PCR거절'
}

// 계약구분 라벨 매핑
const contractCategoryLabels = {
  '단가계약': '단가계약',
  '일반계약': '일반계약',
  '매각계약': '매각계약'
}

// 계약종류 라벨 매핑
const contractTypeLabels = {
  'UP': '자재단가계약',
  'LE': '임대차계약',
  'IL': '개별운송계약',
  'AL': '연간운송계약',
  'OS': '외주용역계약',
  'OW': '도급계약',
  'LO': 'LOI',
  'FA': 'FA',
  'SC': '납품합의계약',
  'OF': '클레임상계계약',
  'AW': '사전작업합의',
  'AD': '사전납품합의',
  'SG': '임치(물품보관)계약',
  'SR': '폐기물매각계약'
}

interface GeneralContractsTableProps {
    promises: Promise<
        [
            Awaited<ReturnType<typeof getGeneralContracts>>,
            Awaited<ReturnType<typeof getGeneralContractStatusCounts>>
        ]
    >
}

export function GeneralContractsTable({ promises }: GeneralContractsTableProps) {
    const [{ data, pageCount }, statusCounts] = React.use(promises)
    const [isCompact, setIsCompact] = React.useState<boolean>(false)
    const [rowAction, setRowAction] = React.useState<DataTableRowAction<GeneralContractListItem> | null>(null)
    const [updateSheetOpen, setUpdateSheetOpen] = React.useState(false)
    const [selectedContract, setSelectedContract] = React.useState<GeneralContractListItem | null>(null)

    console.log(data, "data")

    const router = useRouter()

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

    // rowAction 변경 감지하여 해당 액션 처리
    React.useEffect(() => {
        if (rowAction) {
            setSelectedContract(rowAction.row.original)

            switch (rowAction.type) {
                case "view":
                    // 상세 페이지로 이동
                    router.push(`/evcp/general-contracts/${rowAction.row.original.id}`)
                    break
                case "update":
                    // 수정 시트 열기
                    setSelectedContract(rowAction.row.original)
                    setUpdateSheetOpen(true)
                    break
                default:
                    break
            }
        }
    }, [rowAction, router])

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

    const advancedFilterFields: DataTableAdvancedFilterField<GeneralContractListItem>[] = [
        { id: "name", label: "계약명", type: "text" },
        { id: "contractNumber", label: "계약번호", type: "text" },
        { id: "vendorName", label: "협력업체명", type: "text" },
        { id: "managerName", label: "계약담당자", type: "text" },
        {
            id: "status",
            label: "계약상태",
            type: "multi-select",
            options: Object.entries(contractStatusLabels).map(([value, label]) => ({
                label,
                value,
                count: statusCounts[value] || 0,
            })),
        },
        {
            id: "category",
            label: "계약구분",
            type: "select",
            options: Object.entries(contractCategoryLabels).map(([value, label]) => ({
                label,
                value,
            })),
        },
        {
            id: "type",
            label: "계약종류",
            type: "select",
            options: Object.entries(contractTypeLabels).map(([value, label]) => ({
                label,
                value,
            })),
        },
        {
            id: "executionMethod",
            label: "체결방식",
            type: "select",
            options: GENERAL_EXECUTION_METHODS.map(value => ({
                label: value,
                value: value,
            })),
        },
        {
            id: "contractSourceType",
            label: "업체선정방법",
            type: "select",
            options: [
                { label: "estimate", value: "견적" },
                { label: "bid", value: "입찰" },
                { label: "manual", value: "자체생성" },
            ],
        },
        { id: "registeredAt", label: "계약등록일", type: "date" },
        { id: "signedAt", label: "계약체결일", type: "date" },
        { id: "lastUpdatedAt", label: "최종수정일", type: "date" },
    ]

    const { table } = useDataTable({
        data,
        columns,
        pageCount,
        filterFields,
        enablePinning: true,
        enableAdvancedFilter: true,
        initialState: {
            sorting: [{ id: "registeredAt", desc: true }],
            columnPinning: { right: ["actions"] },
        },
        getRowId: (originalRow) => String(originalRow.id),
        shallow: false,
        clearOnDefault: true,
    })

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

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

            <GeneralContractUpdateSheet
                contract={selectedContract}
                open={updateSheetOpen}
                onOpenChange={setUpdateSheetOpen}
                onSuccess={() => {
                    // 테이블 새로고침 또는 상태 업데이트
                    window.location.reload()
                }}
            />
        </>
    )
}
