"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 { checkAgreementCommentsForContracts } from "@/lib/basic-contract/agreement-comments/actions"
import { checkRedFlagsForContracts } from "@/lib/basic-contract/actions/check-red-flags"
import { checkRedFlagResolutionForContracts } from "@/lib/basic-contract/actions/check-red-flag-resolution"
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 [agreementCommentData, setAgreementCommentData] = React.useState<Record<number, { hasComments: boolean; commentCount: number }>>({})
    const [isLoadingAgreementCommentData, setIsLoadingAgreementCommentData] = React.useState(false)
    
    // Red Flag data 상태 관리
    const [redFlagData, setRedFlagData] = React.useState<Record<number, boolean>>({})
    const [isLoadingRedFlagData, setIsLoadingRedFlagData] = React.useState(false)
    
type RedFlagResolutionState = {
    resolved: boolean
    resolvedAt: Date | null
    pendingApprovalId: string | null
}

    // Red Flag 해제 data 상태 관리
    const [redFlagResolutionData, setRedFlagResolutionData] = React.useState<Record<number, RedFlagResolutionState>>({})
    const [isLoadingRedFlagResolutionData, setIsLoadingRedFlagResolutionData] = React.useState(false)

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

    // 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]);

    // 협의 코멘트 상태 로딩 (준법 포함)
    React.useEffect(() => {
        const loadAgreementComments = async () => {
            if (!data || data.length === 0) return;

            const hasNegotiationTemplates = data.some(contract => 
                contract.templateName?.includes('준법') || contract.templateName?.includes('GTC')
            );

            if (!hasNegotiationTemplates) return;

            setIsLoadingAgreementCommentData(true);
            try {
                const results = await checkAgreementCommentsForContracts(data);
                setAgreementCommentData(results);
            } catch (error) {
                console.error('협의 코멘트 정보를 불러오는데 실패했습니다:', error);
                toast.error("협의 코멘트 정보를 불러오는데 실패했습니다.");
            } finally {
                setIsLoadingAgreementCommentData(false);
            }
        };

        loadAgreementComments();
    }, [data]);

    // Red Flag data 로딩
    React.useEffect(() => {
        const loadRedFlagData = async () => {
            if (!data || data.length === 0) return;
            
            // 준법서약 템플릿이 있는지 확인
            const hasComplianceTemplates = data.some(contract => 
                contract.templateName?.includes('준법')
            );
            
            if (!hasComplianceTemplates) return;
            
            setIsLoadingRedFlagData(true);
            try {
                const redFlagResults = await checkRedFlagsForContracts(data);
                setRedFlagData(redFlagResults);
            } catch (error) {
                console.error('Error checking Red Flag data:', error);
                toast.error("Red Flag 데이터를 불러오는데 실패했습니다.");
            } finally {
                setIsLoadingRedFlagData(false);
            }
        };

        loadRedFlagData();
    }, [data]);

    // Red Flag 해제 data 로딩
    React.useEffect(() => {
        const loadRedFlagResolutionData = async () => {
            if (!data || data.length === 0) return;
            
            // 준법서약 템플릿이 있는지 확인
            const hasComplianceTemplates = data.some(contract => 
                contract.templateName?.includes('준법')
            );
            
            if (!hasComplianceTemplates) return;
            
            setIsLoadingRedFlagResolutionData(true);
            try {
                const resolutionResults = await checkRedFlagResolutionForContracts(data);
                setRedFlagResolutionData(resolutionResults);
            } catch (error) {
                console.error('Error checking Red Flag Resolution data:', error);
                toast.error("Red Flag 해제 데이터를 불러오는데 실패했습니다.");
            } finally {
                setIsLoadingRedFlagResolutionData(false);
            }
        };

        loadRedFlagResolutionData();
    }, [data]);

    // 준법서약 템플릿인지 확인
    const isComplianceTemplate = React.useMemo(() => {
        if (!data || data.length === 0) return false;
        return data.some(contract => contract.templateName?.includes('준법'));
    }, [data]);

    const columns = React.useMemo(
        () => getDetailColumns({ 
            setRowAction, 
            gtcData, 
            isLoadingGtcData,
            agreementCommentData,
            isLoadingAgreementCommentData,
            redFlagData,
            isLoadingRedFlagData,
            redFlagResolutionData,
            isLoadingRedFlagResolutionData,
            isComplianceTemplate,
            router
        }),
        [setRowAction, gtcData, isLoadingGtcData, agreementCommentData, isLoadingAgreementCommentData, redFlagData, isLoadingRedFlagData, redFlagResolutionData, isLoadingRedFlagResolutionData, isComplianceTemplate, 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')) {
                        // GTC 템플릿인 경우 GTC 협의 페이지로 이동
                        // 준법과 동일하게 contract.id를 경로 파라미터로 사용
                        const params = new URLSearchParams();
                        if (contract.templateId) {
                            params.set("templateId", contract.templateId.toString());
                        }
                        if (contract.vendorId) {
                            params.set("vendorId", contract.vendorId.toString());
                        }
                        if (contract.vendorName) {
                            params.set("vendorName", contract.vendorName);
                        }
                        const query = params.toString();
                        const gtcUrl = `/evcp/basic-contract/vendor-gtc/${contract.id}${query ? `?${query}` : ""}`;
                        router.push(gtcUrl);
                    } else if (contract.templateName?.includes('준법')) {
                        // 준법 템플릿인 경우 준법 코멘트 페이지로 이동
                        const params = new URLSearchParams();
                        if (contract.templateId) {
                            params.set("templateId", contract.templateId.toString());
                        }
                        if (contract.vendorId) {
                            params.set("vendorId", contract.vendorId.toString());
                        }
                        if (contract.vendorName) {
                            params.set("vendorName", contract.vendorName);
                        }
                        const query = params.toString();
                        const complianceUrl = `/evcp/basic-contract/compliance-comments/${contract.id}${query ? `?${query}` : ""}`;
                        router.push(complianceUrl);
                    } 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}
                    redFlagData={redFlagData}
                    redFlagResolutionData={redFlagResolutionData}
                    isComplianceTemplate={isComplianceTemplate}
                />
            </DataTableAdvancedToolbar>
        </DataTable>
    )
}