"use client"

import * as React from "react"
import { usePathname, useRouter, useSearchParams, useParams } from "next/navigation"
import { useAtom } from "jotai"
import { selectedModeAtom } from "@/atoms"
import { Sidebar } from "./sidebar"
import { ProjectSwitcher } from "./project-swicher"
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable"
import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { Button } from "@/components/ui/button"
import { TooltipProvider } from "@/components/ui/tooltip"

interface PackageData {
  itemId: number
  itemName: string
}

interface VendorDataContainerProps {
  projects: {
    projectId: number
    projectCode: string
    projectName: string
    projectType: string
    contracts: {
      contractId: number
      contractNo: string
      contractName: string
      packages: PackageData[]
    }[]
  }[]
  defaultLayout?: number[]
  defaultCollapsed?: boolean
  navCollapsedSize?: number
  children: React.ReactNode
}

export function VendorDataContainer({
  projects,
  defaultLayout = [20, 80],
  defaultCollapsed = false,
  navCollapsedSize,
  children
}: VendorDataContainerProps) {
  const pathname = usePathname()
  const router = useRouter()
  const searchParams = useSearchParams()
  const params = useParams()
  const currentLng = params?.lng as string || 'en'

  // 기본 상태
  const [selectedProjectId, setSelectedProjectId] = React.useState(projects[0]?.projectId || 0)
  const [isCollapsed, setIsCollapsed] = React.useState(defaultCollapsed)
  const [selectedContractId, setSelectedContractId] = React.useState(
    projects[0]?.contracts[0]?.contractId || 0
  )
  const [selectedPackageId, setSelectedPackageId] = React.useState<number | null>(null)

  // 현재 선택된 프로젝트/계약/패키지
  const currentProject = projects.find((p) => p.projectId === selectedProjectId) ?? projects[0]
  const currentContract = currentProject?.contracts.find((c) => c.contractId === selectedContractId)
    ?? currentProject?.contracts[0]
    
  // 프로젝트 타입 확인 - ship인 경우 항상 ENG 모드
  const isShipProject = currentProject?.projectType === "ship"
  
  const [selectedMode, setSelectedMode] = useAtom(selectedModeAtom)
  
  // URL에서 모드 추출 (ship 프로젝트면 무조건 ENG로, 아니면 URL 또는 기본값)
  const modeFromUrl = searchParams?.get('mode')
  const initialMode = isShipProject 
    ? "ENG" 
    : (modeFromUrl === "ENG" || modeFromUrl === "IM") ? modeFromUrl : "IM"
  
  // 모드 초기화 (기존의 useState 초기값 대신)
  React.useEffect(() => {
    setSelectedMode(initialMode as "IM" | "ENG")
  }, [initialMode, setSelectedMode])

  // URL에서 모드가 변경되면 상태도 업데이트 (ship 프로젝트가 아닐 때만)
  React.useEffect(() => {
    if (!isShipProject) {
      const modeFromUrl = searchParams?.get('mode')
      if (modeFromUrl === "ENG" || modeFromUrl === "IM") {
        setSelectedMode(modeFromUrl)
      }
    }
  }, [searchParams, isShipProject])

  // 프로젝트 타입이 변경될 때 모드 업데이트
  React.useEffect(() => {
    if (isShipProject) {
      setSelectedMode("ENG")
      
      // URL 모드 파라미터도 업데이트
      const url = new URL(window.location.href);
      url.searchParams.set('mode', 'ENG');
      router.replace(url.pathname + url.search);
    }
  }, [isShipProject, router])

  // (1) 프로젝트 변경 시 계약 초기화
  React.useEffect(() => {
    if (currentProject?.contracts.length) {
      setSelectedContractId(currentProject.contracts[0].contractId)
    } else {
      setSelectedContractId(0)
    }
  }, [currentProject])

  // 핸들러들
  function handleSelectContract(projId: number, cId: number) {
    setSelectedProjectId(projId)
    setSelectedContractId(cId)
  }

  function handleSelectPackage(itemId: number) {
    setSelectedPackageId(itemId)
    
    // partners와 동일하게: 패키지 선택 시 해당 페이지로 이동
    if (itemId && pathname) {
      // 더 안전한 URL 생성 로직
      let baseSegments: string;
      const vendorDataIndex = pathname.split("/").filter(Boolean).indexOf("vendor-data");
      
      if (vendorDataIndex !== -1) {
        baseSegments = pathname.split("/").filter(Boolean).slice(0, vendorDataIndex + 1).join("/");
      } else {
        // vendor-data가 없으면 기본 경로 사용
        baseSegments = `${currentLng}/evcp/vendor-data`;
      }
      
      const targetUrl = `/${baseSegments}/tag/${itemId}?mode=${selectedMode}`;
      router.push(targetUrl);
    }
  }

  function handleSelectForm(formName: string) {
    // partners와 동일하게: 폼 선택 시 해당 페이지로 이동
    if (selectedPackageId && pathname) {
      // 더 안전한 URL 생성 로직
      let baseSegments: string;
      const vendorDataIndex = pathname.split("/").filter(Boolean).indexOf("vendor-data");
      
      if (vendorDataIndex !== -1) {
        baseSegments = pathname.split("/").filter(Boolean).slice(0, vendorDataIndex + 1).join("/");
      } else {
        // vendor-data가 없으면 기본 경로 사용
        baseSegments = `${currentLng}/evcp/vendor-data`;
      }
      
      const targetUrl = `/${baseSegments}/form/${selectedPackageId}/${formName}/${selectedProjectId}/${selectedContractId}?mode=${selectedMode}`;
      router.push(targetUrl);
    }
  }

  // 모드 변경 핸들러
  const handleModeChange = async (mode: "IM" | "ENG") => {
    // ship 프로젝트인 경우 모드 변경 금지
    if (isShipProject && mode !== "ENG") return;
    
    setSelectedMode(mode);
    
    // 모드가 변경될 때 자동 네비게이션
    if (currentContract?.packages?.length) {
      const firstPackageId = currentContract.packages[0].itemId;
      
      if (pathname) {
        // 더 안전한 URL 생성 로직
        let baseSegments: string;
        const vendorDataIndex = pathname.split("/").filter(Boolean).indexOf("vendor-data");
        
        if (vendorDataIndex !== -1) {
          baseSegments = pathname.split("/").filter(Boolean).slice(0, vendorDataIndex + 1).join("/");
        } else {
          // vendor-data가 없으면 기본 경로 사용
          baseSegments = `${currentLng}/evcp/vendor-data`;
        }
        
        const targetUrl = `/${baseSegments}/tag/${firstPackageId}?mode=${mode}`;
        router.push(targetUrl);
      }
    }
  }

  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}
              selectedContractId={selectedContractId}
              onSelectContract={handleSelectContract}
            />
          </div>
          <Separator />
          
          {!isCollapsed ? (
            isShipProject ? (
              // 프로젝트 타입이 ship인 경우: 탭 없이 ENG 모드 사이드바만 바로 표시
              <div className="mt-0">
                <Sidebar
                  isCollapsed={isCollapsed}
                  packages={currentContract?.packages || []}
                  selectedPackageId={selectedPackageId}
                  selectedProjectId={selectedProjectId}
                  selectedContractId={selectedContractId}
                  onSelectPackage={handleSelectPackage}
                  onSelectForm={handleSelectForm}
                  mode="ENG"
                  className="hidden lg:block"
                />
              </div>
            ) : (
              // 프로젝트 타입이 ship이 아닌 경우: 기존 탭 UI 표시
              <Tabs
                defaultValue={initialMode}
                value={selectedMode}
                onValueChange={(value) => handleModeChange(value as "IM" | "ENG")}
                className="w-full"
              >
                <TabsList className="w-full">
                  <TabsTrigger value="IM" className="flex-1">H/O</TabsTrigger>
                  <TabsTrigger value="ENG" className="flex-1">ENG</TabsTrigger>
                </TabsList>
                
                <TabsContent value="IM" className="mt-0">
                  <Sidebar
                    isCollapsed={isCollapsed}
                    packages={currentContract?.packages || []}
                    selectedPackageId={selectedPackageId}
                    selectedContractId={selectedContractId}
                    selectedProjectId={selectedProjectId}
                    onSelectPackage={handleSelectPackage}
                    onSelectForm={handleSelectForm}
                    mode="IM"
                    className="hidden lg:block"
                  />
                </TabsContent>
                
                <TabsContent value="ENG" className="mt-0">
                  <Sidebar
                    isCollapsed={isCollapsed}
                    packages={currentContract?.packages || []}
                    selectedPackageId={selectedPackageId}
                    selectedContractId={selectedContractId}
                    selectedProjectId={selectedProjectId}
                    onSelectPackage={handleSelectPackage}
                    onSelectForm={handleSelectForm}
                    mode="ENG"
                    className="hidden lg:block"
                  />
                </TabsContent>
              </Tabs>
            )
          ) : (
            // 접혀있을 때 UI
            <>
              {!isShipProject && (
                // ship 프로젝트가 아닐 때만 모드 선택 버튼 표시
                <div className="flex justify-center space-x-1 my-2">
                  <Button 
                    variant={selectedMode === "IM" ? "default" : "ghost"} 
                    size="sm"
                    className="h-8 px-2"
                    onClick={() => handleModeChange("IM")}
                  >
                    H/O
                  </Button>
                  <Button 
                    variant={selectedMode === "ENG" ? "default" : "ghost"} 
                    size="sm"
                    className="h-8 px-2"
                    onClick={() => handleModeChange("ENG")}
                  >
                    ENG
                  </Button>
                </div>
              )}
              
              <Sidebar
                isCollapsed={isCollapsed}
                packages={currentContract?.packages || []}
                selectedPackageId={selectedPackageId}
                selectedProjectId={selectedProjectId}
                selectedContractId={selectedContractId}
                onSelectPackage={handleSelectPackage}
                onSelectForm={handleSelectForm}
                mode={isShipProject ? "ENG" : selectedMode}
                className="hidden lg:block"
              />
            </>
          )}
        </ResizablePanel>

        <ResizableHandle withHandle />

        <ResizablePanel defaultSize={defaultLayout[1]} minSize={40}>
          <div className="p-4 h-full overflow-auto flex flex-col">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold">
                {isShipProject || selectedMode === "ENG" 
                  ? "Engineering Mode" 
                  : `Package: ${currentContract?.packages.find((pkg) => pkg.itemId === selectedPackageId)?.itemName || "None"}`}
              </h2>
            </div>
            {children}
          </div>
        </ResizablePanel>
      </ResizablePanelGroup>
    </TooltipProvider>
  )
}