"use client"
import * as React from "react"
import { useRouter, useParams } from "next/navigation"
import { ProjectSelector } from "../ProjectSelector"
import { useTranslation } from "@/i18n/client"

interface DocuListRuleClientProps {
    children: React.ReactNode;
}

export default function DocuListRuleClient({
    children,
}: DocuListRuleClientProps) {
    const router = useRouter()
    const params = useParams()
    const lng = (params?.lng as string) || "ko"
    const { t } = useTranslation(lng, 'menu')
    // Get the projectId from route parameters
    const projectIdFromUrl = React.useMemo(() => {
        if (params?.projectId) {
            const projectId = Array.isArray(params.projectId) 
                ? params.projectId[0] 
                : params.projectId
            return Number(projectId)
        }
        return null
    }, [params])
    
    // Use the URL projectId as the selected project
    const [selectedProjectId, setSelectedProjectId] = React.useState<number | null>(
        projectIdFromUrl
    )
    
    // Update selectedProjectId when URL changes
    React.useEffect(() => {
        if (projectIdFromUrl) {
            setSelectedProjectId(projectIdFromUrl)
        }
    }, [projectIdFromUrl])

    // Handle project selection
    function handleSelectProject(projectId: number) {
        console.log("Selecting project:", projectId)
        setSelectedProjectId(projectId)
        
        // Navigate to the project's document-class page
        router.push(`/${lng}/evcp/docu-list-rule/${projectId}`)
    }
    
    return (
        <>
            {/* 상단 영역: 제목 왼쪽 / ProjectSwitcher 오른쪽 */}
            <div className="flex items-center justify-between">
                {/* 왼쪽: 타이틀 & 설명 */}
                <div>
                    <div className="flex items-center gap-2">
                        <h2 className="text-2xl font-bold tracking-tight">{t('menu.master_data.document_numbering_rule')}</h2>
                    </div>
                    <p className="text-muted-foreground">
                    {t('menu.master_data.document_numbering_rule_desc')}
                    </p>
                </div>
                
                {/* 오른쪽: ProjectSwitcher */}
                <div className="flex items-center space-x-2 max-w-[400px]">
                    <ProjectSelector 
                        selectedProjectId={selectedProjectId}
                        onProjectSelect={(project) => {
                            handleSelectProject(project.id)
                        }}
                        placeholder="프로젝트를 선택하세요"
                        filterType="plant"  // 명시적으로 plant 타입만 (선택사항, 기본값이 plant)

                    />
                </div>
            </div>
            
            {/* 문서 목록/테이블 영역 */}
            <section className="overflow-hidden rounded-[0.5rem] border bg-background shadow p-5">
                {children}
            </section>
        </>
    )
}