"use client"

import * as React from "react"
import { DataTable } from "@/components/data-table/data-table"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import type {
    DataTableAdvancedFilterField,
    DataTableRowAction,
} from "@/types/table"
import { getDetailColumns } from "./basic-contracts-detail-columns"
import { getBasicContractsByTemplateId } from "@/lib/basic-contract/service"
import { checkGTCCommentsForContracts } from "@/lib/basic-contract/actions/check-gtc-comments"
import { BasicContractView } from "@/db/schema"
import { BasicContractDetailTableToolbarActions } from "./basic-contract-detail-table-toolbar-actions"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

interface BasicContractsDetailTableProps {
    templateId: number
    promises: Promise<
        [
            Awaited<ReturnType<typeof getBasicContractsByTemplateId>>,
        ]
    >
}

export function BasicContractsDetailTable({ templateId, promises }: BasicContractsDetailTableProps) {
    const [rowAction, setRowAction] =
        React.useState<DataTableRowAction<BasicContractView> | null>(null)
    
    // GTC data 상태 관리
    const [gtcData, setGtcData] = React.useState<Record<number, { gtcDocumentId: number | null; hasComments: boolean }>>({})
    const [isLoadingGtcData, setIsLoadingGtcData] = React.useState(false)

    const [{ data, pageCount }] = React.use(promises)
    const router = useRouter()

    console.log(gtcData, "gtcData")
    console.log(data, "data")

    // GTC data 로딩
    React.useEffect(() => {
        const loadGtcData = async () => {
            if (!data || data.length === 0) return;
            
            // GTC가 포함된 template이 있는지 확인
            const hasGtcTemplates = data.some(contract => 
                contract.templateName?.includes('GTC')
            );
            
            if (!hasGtcTemplates) return;
            
            setIsLoadingGtcData(true);
            try {
                const gtcResults = await checkGTCCommentsForContracts(data);
                setGtcData(gtcResults);
            } catch (error) {
                console.error('Error checking GTC data:', error);
                toast.error("GTC 데이터를 불러오는데 실패했습니다.");
            } finally {
                setIsLoadingGtcData(false);
            }
        };

        loadGtcData();
    }, [data]);

    const columns = React.useMemo(
        () => getDetailColumns({ 
            setRowAction, 
            gtcData, 
            isLoadingGtcData ,
            router
        }),
        [setRowAction, gtcData, isLoadingGtcData, router]
    )

    const advancedFilterFields: DataTableAdvancedFilterField<BasicContractView>[] = [
        { id: "vendorName", label: "업체명", type: "text" },
        { id: "vendorCode", label: "업체코드", type: "text" },
        {
            id: "status",
            label: "진행상태",
            type: "select",
            options: [
                { label: "발송완료", value: "PENDING" },
                { label: "협력업체 서명완료", value: "VENDOR_SIGNED" },
                { label: "구매팀 서명완료", value: "BUYER_SIGNED" },
                { label: "법무검토 요청", value: "LEGAL_REVIEW_REQUESTED" },
                { label: "법무검토 완료", value: "LEGAL_REVIEW_COMPLETED" },
                { label: "계약완료", value: "COMPLETED" },
                { label: "거절됨", value: "REJECTED" },
            ]
        },
        { id: "requestedByName", label: "요청자", type: "text" },
        { id: "createdAt", label: "요청일", type: "date" },
        { id: "deadline", label: "마감일", type: "date" },
        { id: "vendorSignedAt", label: "협력업체 서명일", type: "date" },
        { id: "buyerSignedAt", label: "구매팀 서명일", type: "date" },
        { id: "completedAt", label: "계약완료일", type: "date" },
    ]

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

    // rowAction 처리 로직 추가
    React.useEffect(() => {
        if (rowAction) {
            switch (rowAction.type) {
                case "view":
                    // GTC 템플릿인 경우 GTC 협의 페이지로 이동
                    const contract = rowAction.row.original;
                    if (contract.templateName?.includes('GTC')) {
                        const contractGtcData = gtcData[contract.id];
                        if (contractGtcData?.gtcDocumentId) {
                            const gtcUrl = `/evcp/basic-contract/vendor-gtc/${contractGtcData.gtcDocumentId}?vendorId=${contract.vendorId}&vendorName=${encodeURIComponent(contract.vendorName || '')}&contractId=${contract.id}&templateId=${contract.templateId}`;
                            router.push(gtcUrl);
                        } else {
                            toast.error("GTC 문서 정보를 찾을 수 없습니다.");
                        }
                    } else {
                        // 일반 계약서인 경우: 상세 정보를 보여주는 기능
                        // 현재는 준비 중이지만, 향후 다이얼로그나 시트를 열 수 있음
                        toast.info("상세 정보 기능은 준비 중입니다.");
                    }
                    setRowAction(null);
                    break;
                default:
                    setRowAction(null);
                    break;
            }
        }
    }, [rowAction, router, gtcData]);

    return (
        <DataTable table={table}>
            <DataTableAdvancedToolbar
                table={table}
                filterFields={advancedFilterFields}
            >
                <BasicContractDetailTableToolbarActions table={table} gtcData={gtcData} />
            </DataTableAdvancedToolbar>
        </DataTable>
    )
}