"use client"

import * as React from "react"
import { TooltipProvider } from "@/components/ui/tooltip"
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable"
import { cn } from "@/lib/utils"
import { Sidebar } from "./sidebar"
import { usePathname, useRouter } from "next/navigation"
import { Separator } from "@/components/ui/separator"
import { ProjectSwitcher } from "./project-swicher"

interface PackageData {
  packageCode: string
  packageName: string | null
}

interface ProjectData {
  projectId: number
  projectCode: string
  projectName: string
  projectType: string
  packages: PackageData[]
}

interface VendorDataContainerProps {
  projects: ProjectData[]
  defaultLayout?: number[]
  defaultCollapsed?: boolean
  navCollapsedSize: number
  children: React.ReactNode
}

function getInfoFromPathname(path: string | null): {
  projectCode: string | null
  packageCode: string | null
  formCode: string | null
  mode: "master" | "engineering" | "im" | null
} {
  if (!path) return { projectCode: null, packageCode: null, formCode: null, mode: null }
  
  const segments = path.split("/").filter(Boolean)
  const vendorDataIndex = segments.indexOf("vendor-data-plant")
  
  if (vendorDataIndex === -1) {
    return { projectCode: null, packageCode: null, formCode: null, mode: null }
  }
  
  const projectCode = segments[vendorDataIndex + 1] || null
  const packageCode = segments[vendorDataIndex + 2] || null
  
  // /eng/{formCode} 또는 /im/{formCode} 패턴 체크
  const modeSegment = segments[vendorDataIndex + 3]
  const formCode = segments[vendorDataIndex + 4] || null
  
  let mode: "master" | "engineering" | "im" | null = null
  
  if (modeSegment === "eng") {
    mode = "engineering"
  } else if (modeSegment === "im") {
    mode = "im"
  } else if (projectCode && packageCode && !modeSegment) {
    mode = "master"
  }
  
  return { projectCode, packageCode, formCode, mode }
}

export function VendorDataContainer({
  projects,
  defaultLayout = [20, 80],
  defaultCollapsed = false,
  navCollapsedSize,
  children
}: VendorDataContainerProps) {
  const pathname = usePathname()
  const router = useRouter()

  // 상태 관리
  const [selectedProjectId, setSelectedProjectId] = React.useState(projects[0]?.projectId || 0)
  const [selectedProjectCode, setSelectedProjectCode] = React.useState(projects[0]?.projectCode || "")
  const [isCollapsed, setIsCollapsed] = React.useState(defaultCollapsed)
  const [selectedPackageCode, setSelectedPackageCode] = React.useState<string | null>(null)
  const [selectedFormCode, setSelectedFormCode] = React.useState<string | null>(null)
  const [currentMode, setCurrentMode] = React.useState<"master" | "engineering" | "im" | null>(null)

  // 현재 선택된 프로젝트
  const currentProject = projects.find((p) => p.projectId === selectedProjectId) ?? projects[0]

  // URL 변경 시 상태 동기화
  React.useEffect(() => {
    const { projectCode, packageCode, formCode, mode } = getInfoFromPathname(pathname)
    
    if (projectCode && packageCode) {
      // 프로젝트 찾기
      const project = projects.find(p => p.projectCode === projectCode)
      if (project) {
        setSelectedProjectId(project.projectId)
        setSelectedProjectCode(project.projectCode)
        setSelectedPackageCode(packageCode)
      }
    }
    
    if (formCode) {
      setSelectedFormCode(formCode)
    } else {
      setSelectedFormCode(null)
    }
    
    if (mode) {
      setCurrentMode(mode)
    } else {
      setCurrentMode(null)
    }
  }, [pathname, projects])

  // 베이스 URL 생성 헬퍼
  const getBaseUrl = () => {
    const segments = pathname?.split("/").filter(Boolean) || []
    const vendorDataIndex = segments.indexOf("vendor-data-plant")
    if (vendorDataIndex === -1) return ""
    return "/" + segments.slice(0, vendorDataIndex + 1).join("/")
  }

  // 프로젝트 및 패키지 선택 핸들러
  const handleSelectPackage = (projectId: number, packageCode: string) => {
    const project = projects.find(p => p.projectId === projectId)
    if (!project) return
    
    setSelectedProjectId(projectId)
    setSelectedPackageCode(packageCode)
    setSelectedFormCode(null)
    setCurrentMode("master")
    
    const baseUrl = getBaseUrl()
    router.push(`${baseUrl}/${project.projectCode}/${packageCode}`)
  }
  
  // Master Tag List 클릭 핸들러
  const handleMasterTagListClick = () => {
    if (!selectedPackageCode) return
    
    const project = projects.find(p => p.projectId === selectedProjectId)
    if (!project) return
    
    setCurrentMode("master")
    setSelectedFormCode(null)
    
    const baseUrl = getBaseUrl()
    router.push(`${baseUrl}/${project.projectCode}/${selectedPackageCode}`)
  }
  
  // Engineering 폼 클릭 핸들러
  const handleEngineeringFormClick = (formCode: string) => {
    if (!selectedPackageCode) return
    
    const project = projects.find(p => p.projectId === selectedProjectId)
    if (!project) return
    
    setCurrentMode("engineering")
    setSelectedFormCode(formCode)
    
    const baseUrl = getBaseUrl()
    router.push(`${baseUrl}/${project.projectCode}/${selectedPackageCode}/eng/${formCode}`)
  }
  
  // IM 폼 클릭 핸들러
  const handleIMFormClick = (formCode: string) => {
    if (!selectedPackageCode) return
    
    const project = projects.find(p => p.projectId === selectedProjectId)
    if (!project) return
    
    setCurrentMode("im")
    setSelectedFormCode(formCode)
    
    const baseUrl = getBaseUrl()
    router.push(`${baseUrl}/${project.projectCode}/${selectedPackageCode}/im/${formCode}`)
  }

  return (
    <TooltipProvider delayDuration={0}>
      <ResizablePanelGroup direction="horizontal" className="h-full">
        <ResizablePanel
          defaultSize={defaultLayout[0]}
          collapsedSize={navCollapsedSize}
          collapsible
          minSize={15}
          maxSize={25}
          onCollapse={() => setIsCollapsed(true)}
          onResize={() => setIsCollapsed(false)}
          className={cn(isCollapsed && "min-w-[50px] transition-all duration-300 ease-in-out")}
        >
          <div
            className={cn(
              "flex h-[52px] items-center justify-center gap-2",
              isCollapsed ? "h-[52px]" : "px-2"
            )}
          >
            <ProjectSwitcher
              isCollapsed={isCollapsed}
              projects={projects}
              selectedProjectId={selectedProjectId}
              selectedPackageCode={selectedPackageCode}
              onSelectPackage={handleSelectPackage}
            />
          </div>
          <Separator />
          
          <Sidebar
            isCollapsed={isCollapsed}
            selectedPackageCode={selectedPackageCode}
            projectCode={selectedProjectCode}
            selectedFormCode={selectedFormCode}
            currentMode={currentMode}
            onMasterTagListClick={handleMasterTagListClick}
            onEngineeringFormClick={handleEngineeringFormClick}
            onIMFormClick={handleIMFormClick}
          />
        </ResizablePanel>

        <ResizableHandle withHandle />

        <ResizablePanel defaultSize={defaultLayout[1]} minSize={40}>
          <div className="p-4 h-full overflow-auto flex flex-col">
            {children}
          </div>
        </ResizablePanel>
      </ResizablePanelGroup>
    </TooltipProvider>
  )
}