"use client"

import * as React from "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 { getSHIEvaluationSubmissions } from "../service"
import { getColumns } from "./evaluation-submissions-table-columns"
import { useRouter } from "next/navigation"
import { ReviewerEvaluationView } from "@/db/schema"

interface EvaluationSubmissionsTableProps {
    promises: Promise<
        [
            Awaited<ReturnType<typeof getSHIEvaluationSubmissions>>,
        ]
    >
}

export function SHIEvaluationSubmissionsTable({ promises }: EvaluationSubmissionsTableProps) {
    // 1. 데이터 로딩 상태 관리
    const [isLoading, setIsLoading] = React.useState(true)
    const [tableData, setTableData] = React.useState<{
        data: ReviewerEvaluationView[]
        pageCount: number
    }>({ data: [], pageCount: 0 })
    const router = useRouter()

    console.log(tableData)


    // 2. 행 액션 상태 관리
    const [rowAction, setRowAction] =
        React.useState<DataTableRowAction<ReviewerEvaluationView> | null>(null)

    // 3. Promise 해결을 useEffect로 처리
    React.useEffect(() => {
        promises
            .then(([result]) => {
                setTableData(result)
                setIsLoading(false)
            })
            // .catch((error) => {
            //     console.error('Failed to load evaluation submissions:', error)
            //     setIsLoading(false)
            // })
    }, [promises])

    // 4. 컬럼 정의
    const columns = React.useMemo(
        () => getColumns({ setRowAction , router}),
        [setRowAction, router]
    )

    // 5. 필터 필드 정의
    const filterFields: DataTableFilterField<ReviewerEvaluationView>[] = [
        {
            id: "isCompleted",
            label: "완료상태",
            placeholder: "완료상태 선택...",
        },
        {
            id: "periodicStatus", 
            label: "정기평가 상태",
            placeholder: "상태 선택...",
        },
        {
            id: "evaluationYear",
            label: "평가연도",
            placeholder: "연도 선택...",
        },
        {
            id: "departmentCode",
            label: "담당부서",
            placeholder: "부서 선택...",
        },
    ]

    const advancedFilterFields: DataTableAdvancedFilterField<ReviewerEvaluationView>[] = [
        {
            id: "reviewerEvaluationId",
            label: "평가 ID",
            type: "text",
        },
        {
            id: "vendorName",
            label: "협력업체명",
            type: "text",
        },
        {
            id: "vendorCode",
            label: "협력업체 코드",
            type: "text",
        },
        {
            id: "evaluationYear",
            label: "평가연도",
            type: "number",
        },
        {
            id: "departmentCode",
            label: "부서코드",
            type: "select",
            options: [
                { label: "구매평가", value: "ORDER_EVAL" },
                { label: "조달평가", value: "PROCUREMENT_EVAL" },
                { label: "품질평가", value: "QUALITY_EVAL" },
                { label: "CS평가", value: "CS_EVAL" },
                { label: "관리자", value: "ADMIN_EVAL" },
            ],
        },
        {
            id: "division",
            label: "사업부",
            type: "select", 
            options: [
                { label: "조선", value: "SHIP" },
                { label: "플랜트", value: "PLANT" },
            ],
        },
        {
            id: "materialType",
            label: "자재유형",
            type: "select",
            options: [
                { label: "장비", value: "EQUIPMENT" },
                { label: "벌크", value: "BULK" },
                { label: "장비+벌크", value: "EQUIPMENT_BULK" },
            ],
        },
        {
            id: "domesticForeign",
            label: "국내/해외",
            type: "select",
            options: [
                { label: "국내", value: "DOMESTIC" },
                { label: "해외", value: "FOREIGN" },
            ],
        },
        {
            id: "isCompleted",
            label: "평가완료 여부",
            type: "select",
            options: [
                { label: "완료", value: "true" },
                { label: "미완료", value: "false" },
            ],
        },
        {
            id: "periodicStatus",
            label: "정기평가 상태",
            type: "select",
            options: [
                { label: "대기중", value: "PENDING" },
                { label: "진행중", value: "IN_PROGRESS" },
                { label: "검토중", value: "REVIEW" },
                { label: "완료", value: "COMPLETED" },
            ],
        },
        {
            id: "documentsSubmitted",
            label: "문서 제출여부",
            type: "select",
            options: [
                { label: "제출완료", value: "true" },
                { label: "미제출", value: "false" },
            ],
        },
        {
            id: "periodicFinalScore",
            label: "최종점수",
            type: "number",
        },
        {
            id: "periodicFinalGrade",
            label: "최종등급",
            type: "text",
        },
        {
            id: "ldClaimCount",
            label: "LD 클레임 건수",
            type: "number",
        },
        {
            id: "submissionDate",
            label: "제출일",
            type: "date",
        },
        {
            id: "submissionDeadline",
            label: "제출마감일",
            type: "date",
        },
        {
            id: "completedAt",
            label: "완료일시",
            type: "date",
        },
        {
            id: "reviewerEvaluationCreatedAt",
            label: "생성일",
            type: "date",
        },
        {
            id: "reviewerEvaluationUpdatedAt",
            label: "수정일",
            type: "date",
        },
    ]

    // 6. 데이터 테이블 설정
    const { table } = useDataTable({
        data: tableData.data,
        columns,
        pageCount: tableData.pageCount,
        filterFields,
        enablePinning: true,
        enableAdvancedFilter: true,
        initialState: {
            sorting: [{ id: "reviewerEvaluationUpdatedAt", desc: true }],
            columnPinning: { left: ["select"], right: ["actions"] },
        },
        getRowId: (originalRow) => String(originalRow.reviewerEvaluationId),
        shallow: false,
        clearOnDefault: true,
    })

    // 7. 데이터 새로고침 함수
    const handleRefresh = React.useCallback(() => {
        setIsLoading(true)
        router.refresh()
    }, [router])

    // 8. 각종 성공 핸들러
    const handleActionSuccess = React.useCallback(() => {
        setRowAction(null)
        table.resetRowSelection()
        handleRefresh()
    }, [handleRefresh, table])

    // 9. 로딩 상태 표시
    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-32">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                <span className="ml-2">평가 제출 목록을 불러오는 중...</span>
            </div>
        )
    }

    return (
        <>
            {/* 메인 테이블 */}
            <DataTable table={table}>
                <DataTableAdvancedToolbar
                    table={table}
                    filterFields={advancedFilterFields}
                    shallow={false}
                >
                    {/* 추가 툴바 버튼들이 필요하면 여기에 */}
                </DataTableAdvancedToolbar>
            </DataTable>

            {/* 행 액션 모달들 - 필요에 따라 구현 */}
            {/* {rowAction?.type === "view_detail" && (
                <EvaluationDetailDialog
                    row={rowAction.row}
                    onClose={() => setRowAction(null)}
                    onSuccess={handleActionSuccess}
                />
            )} */}
        </>
    )
}